<?php
/**
 * Created by muniao.
 * User: muniao
 * Date: 2018/7/25
 * Time: 9:48
 */

namespace app\api\controller\deliver\v1;


use app\api\model\Authority;

use app\api\model\Common;
use app\api\model\OrderDeliveryManagerModel;
use app\api\model\OrderModel;
use app\api\model\Reimbursement;
use app\index\model\Jpush;
use constant\config;
use Doctrine\ORM\EntityManager;
use redis\RedisPackage;
use think\Cache;
use think\Controller;
use app\api\model\Capital;
use think\Request;
use think\Exception;
use app\api\validate;
use  app\api\model\Approval;
use Think\Db;


class MaterialScience extends Controller
{
    protected $model;
    protected $us;
    protected $newTime;
    protected $endTime;
    protected $overtime;
    protected $pdf;
    
    
    public function _initialize()
    {
        $this->model = new Authority();
        
        $this->us = Authority::check(1);
        
    }
    
    
    /**
     * 获取库存列表
     */
    public function Stock_list()
    {
        $data = Request::instance()->post(['type', 'ok']);
        if ($data['type'] == 0) {
            $custom = db('custom_material')->field('id,company,stock_name,latest_cost,number,created_time,number')->where(['store_id' => $this->us['store_id'], 'status' => 0])->where('number', 'neq', 0)->select();
            foreach ($custom as $k => $l) {
                $custom[$k]['type'] = 0;
            }
        } else if ($data['type'] == 99) {
            $cust = db('purchase_usage')->field('id,company,stock_name,latest_cost,number,created_time,content,remake')->where('type', 1)->where('number', 'neq', 0);
            if (isset($data['ok']) && $data['ok'] != '') {
                $cust->where(['status' => 3]);
            }
            $custom = $cust->where('store_id', $this->us['store_id'])->order('created_time desc')->select();
            foreach ($custom as $k => $l) {
                $custom[$k]['type'] = 99;
            }
        } else if ($data['type'] == 98) {
            $cooperation_usage = db('cooperation_usage')->join('stock', 'stock.id=cooperation_usage.stock_id', 'left')->field('cooperation_usage.id,cooperation_usage.company,cooperation_usage.stock_name,cooperation_usage.stock_id,cooperation_usage.latest_cost,sum(cooperation_usage.number) as number,cooperation_usage.created_time,cooperation_usage.remake,stock.type')->where('stock.type', $data['type'])->group('cooperation_usage.latest_cost,cooperation_usage.stock_id');
            
            if (isset($data['ok']) && $data['ok'] != '') {
                $cooperation_usage->where(['cooperation_usage.status' => 3]);
            }
            $custom = $cooperation_usage->order('cooperation_usage.created_time desc')->select();
        } else {
            $custom = db('routine_usage')->join('stock', 'stock.id=routine_usage.stock_id', 'left')->field('routine_usage.id,routine_usage.company,routine_usage.stock_name,routine_usage.stock_id,routine_usage.latest_cost,sum(routine_usage.number) as number,routine_usage.created_time,routine_usage.remake,stock.type')->where('routine_usage.store_id', $this->us['store_id'])->where('stock.type', $data['type'])->group('routine_usage.latest_cost,routine_usage.stock_id')->where('routine_usage.status', 3)->select();
            
        }
        
        r_date($custom, 200);
    }
    
    /**
     * 获取库存列表
     */
    public function Stock_list_search()
    {
        $data            = Request::instance()->post(['title']);
        $custom_material = [];
        $purchase_usage  = [];
        $routine_usage   = [];
        $custom_material = db('custom_material')->field('id,company,stock_name,latest_cost,number,created_time,number')->where(['store_id' => $this->us['store_id'], 'status' => 0])->where(['stock_name' => ['like', "%{$data['title']}%"]])->where('number', 'neq', 0)->select();
        foreach ($custom_material as $k => $l) {
            $custom_material[$k]['type'] = 0;
        }
        
        $purchase_usage = db('purchase_usage')->field('id,company,stock_name,latest_cost,number,created_time,status,content,remake')->where('type', 1)->where('number', 'neq', 0)->where('status', 3)->where(['stock_name' => ['like', "%{$data['title']}%"]])->where('store_id', $this->us['store_id'])->select();
        foreach ($purchase_usage as $k => $l) {
            $purchase_usage[$k]['type'] = 99;
        }
        
        $routine_usage = db('routine_usage')->join('stock', 'stock.id=routine_usage.stock_id', 'left')->field('routine_usage.id,routine_usage.company,routine_usage.stock_name,routine_usage.stock_id,routine_usage.latest_cost,sum(routine_usage.number) as number,routine_usage.created_time,routine_usage.remake,stock.type')->where('routine_usage.store_id', $this->us['store_id'])->where(['routine_usage.stock_name' => ['like', "%{$data['title']}%"]])->group('routine_usage.latest_cost,routine_usage.stock_id')->where('routine_usage.status', 3)->select();
        
        $cooperation_usage = db('cooperation_usage')->join('stock', 'stock.id=cooperation_usage.stock_id', 'left')->field('cooperation_usage.id,cooperation_usage.company,cooperation_usage.stock_name,cooperation_usage.stock_id,cooperation_usage.latest_cost,sum(cooperation_usage.number) as number,cooperation_usage.created_time,cooperation_usage.remake,stock.type')->group('cooperation_usage.latest_cost,cooperation_usage.stock_id')->where(['cooperation_usage.stock_name' => ['like', "%{$data['title']}%"]])->where('cooperation_usage.status', 3)->order('cooperation_usage.created_time desc')->select();
        
        
        r_date(array_merge(array_merge(array_merge($custom_material, $purchase_usage), $routine_usage), $cooperation_usage), 200);
    }
    
    /*
     * 获取盘点数据
     */
    public function InventoryData()
    {
        $store_inventory = db('store_inventory', config('database.zong'))->where('store_id', $this->us['store_id'])->order('created_time desc')->find();
        $u8c_special4r   = db('u8c_special4r', config('database.zong'))->where('store_id', $this->us['store_id'])->field('invcl_name,invcl_code as invclCode,flag,shop_completion_time,round(sum((check_num-nabnum)*nabprice),2) as  illustrates,sum(if(flag=1,1,0)) as Counted,count(*) as count')->where('month', $store_inventory['month'])->where('year', $store_inventory['year'])->group('invcl_code,month')->order('id asc')->select();
        $illustratesSum=0;
        foreach ($u8c_special4r as $k => $item) {
//            $number=db('u8c_special4r', config('database.zong'))->where('store_id', $this->us['store_id'])->where('month',$store_inventory['month'])->where('invcl_code',$item['invclCode'])->field('sum(if(flag=1,1,0)) as Counted,count(*) as count')->group('invcl_code')->order('nabnum desc')->select();
            $flag = 0;
            if ($item['Counted'] == $item['count']) {
                $illustratesSum +=$item['illustrates'];
                $flag = 1;
            }
            $u8c_special4r[$k]['flag'] = $flag;
//           $illustrates=bcsub(bcsub($item['check_num'],$item['nabnum'],2),$item['nabprice'],2);
            if ($item['illustrates'] < 0) {
                $illustrate = '盘亏(' . $item['illustrates'] . '元)';;
            } elseif ($item['illustrates'] == 0) {
                $illustrate = '盘平';;
            } else {
                $illustrate = '盘赢(' . $item['illustrates'] . '元)';;
            }
            $u8c_special4r[$k]['illustrate'] = $illustrate;
            
        }
        if ($illustratesSum < 0) {
            $illustratesSum = '盘亏(' . $illustratesSum . '元)';;
        } elseif ($illustratesSum == 0) {
            $illustratesSum = '盘平';;
        } else {
            $illustratesSum = '盘赢(' . $illustratesSum . '元)';;
        }
        r_date(['data' => $u8c_special4r, 'inventory' => $this->us['Inventory'], 'startTime' => date('Y-m-d H:i', $store_inventory['begin_time']), 'endTime' => date('Y-m-d H:i', $store_inventory['end_time']), 'allComplete' => empty($u8c_special4r[0]['shop_completion_time']) ? 0 : 1, 'illustrateSum' => $illustratesSum, 'completionTime' => empty($u8c_special4r[0]['shop_completion_time']) ? '' : date('Y-m-d H:i:s', $u8c_special4r[0]['shop_completion_time'])], 200);
    }
    
    /*
     * 获取盘点数据
     */
    public function InventoryDataInfo()
    {
        $data            = Authority::param(['invclCode']);
        $store_inventory = db('store_inventory', config('database.zong'))->where('store_id', $this->us['store_id'])->order('created_time desc')->find();
        $u8c_special4r   = db('u8c_special4r', config('database.zong'))->where('store_id', $this->us['store_id'])->where('invcl_code', $data['invclCode'])->where('month', $store_inventory['month'])->where('year', $store_inventory['year'])->field('invname,nabnum,nabprice,measname,id,flag,check_num as checkNum,invcl_code as invclcode')->order('nabnum desc')->select();
        r_date($u8c_special4r, 200);
    }
    
    /*
    * 获取盘点数据t提价
    */
    public function InventoryDataSubmit()
    {
        
        $list = special4r($this->us['store_id']);
        if ($list['code'] == 0) {
            $store_inventory = db('store_inventory', config('database.zong'))->where('store_id', $this->us['store_id'])->order('created_time desc')->find();
            db('u8c_special4r', config('database.zong'))->where('month', $store_inventory['month'])->where('year', $store_inventory['year'])->where('store_id', $this->us['store_id'])->update(['shop_completion_time' => time()]);
            r_date(NULL, 200);
        }
        r_date(NULL, 300, $list['msg']);
    }
    
    /*
    * 获取盘点数据t提价
    */
    public function InventoryInfoAllSubmit()
    {
        $data  = Authority::param(['invclCode']);
        $store_inventory = db('store_inventory', config('database.zong'))->where('store_id', $this->us['store_id'])->order('created_time desc')->find();
        $u8c_special4r=db('u8c_special4r', config('database.zong'))->where('store_id', $this->us['store_id'])->where('year', $store_inventory['year'])->where('month', $store_inventory['month'])->where('invcl_code', $data['invclCode'])->find();
        if($u8c_special4r['shop_completion_time'] !=0){
            r_date(NULL, 300, "店铺盘点已完成，不可修改");
        }
        $where = [
            'check_num' => Db::raw('nabnum'),
            'flag' => 1,
            'classification_completion_time' => time(),
        ];
        db('u8c_special4r', config('database.zong'))->where('store_id', $this->us['store_id'])->where('invcl_code', $data['invclCode'])->where('flag', 0)->update($where);
        r_date(NULL, 200);
    }
    
    /*
   * 获取盘点数据t提价
   */
    public function InventoryInfoSubmit()
    {
        $data = Authority::param(['id', 'checkNum']);
        $u8c_special4r= db('u8c_special4r', config('database.zong'))->where('id', $data['id'])->find();
        if($u8c_special4r['shop_completion_time'] !=0){
            r_date(NULL, 300, "店铺盘点已完成，不可修改");
        }
        $check_num=$data['checkNum'];
        if($check_num>1){
            $check_num=ltrim($data['checkNum'], '0');
        }
        db('u8c_special4r', config('database.zong'))->where('id', $data['id'])->update(['check_num' => $check_num, 'flag' => 1, 'classification_completion_time' => time()]);
        r_date(NULL, 200);
    }
    
    /**
     * 获取库存列表
     */
    public function CollectingStock_list()
    {
        $data = Request::instance()->post(['type', 'ok']);
        if ($data['type'] == 0) {
            $custom = db('custom_material')->field('id,company,stock_name,status,latest_cost,number,created_time,number')->where(['store_id' => $this->us['store_id'], 'status' => 0])->where('number', 'neq', 0)->select();
            foreach ($custom as $k => $l) {
                $custom[$k]['type'] = 0;
            }
        } else if ($data['type'] == 99) {
            $cust = db('purchase_usage')->field('id,company,stock_name,status,latest_cost,number,created_time,content,remake')->where('type', 1)->where('number', 'neq', 0);
            if (isset($data['ok']) && $data['ok'] != '') {
                $cust->where(['status' => 3]);
            }
            $custom = $cust->where('store_id', $this->us['store_id'])->order('created_time desc')->select();
            foreach ($custom as $k => $l) {
                $custom[$k]['type'] = 99;
            }
        } else if ($data['type'] == 98) {
            $custom = db('stock')->field('id,company,stock_name,latest_cost,type,class_table')->where('type', 98)->whereNull('deleted_at')->select();
            foreach ($custom as $k => $value) {
                $custom[$k]['latest_cost'] = !empty($value['latest_cost']) ? $value['latest_cost'] : 0;
                $custom[$k]['number']      = db('cooperation_usage')->where('stock_id', $value['id'])->where('status', 3)->sum('number');
                $custom[$k]['state']       = db('cooperation_usage')->where('stock_id', $value['id'])->where('status', 3)->value('status');
            }
        } else {
            $custom = db('stock')->field('id,company,stock_name,latest_cost,type,class_table')->where('type', $data['type'])->whereNull('deleted_at')->select();
            
            foreach ($custom as $k => $value) {
                $custom[$k]['latest_cost'] = !empty($value['latest_cost']) ? $value['latest_cost'] : 0;
                $custom[$k]['number']      = db('routine_usage')->where('store_id', $this->us['store_id'])->where('stock_id', $value['id'])->where('status', 3)->sum('number');
                $custom[$k]['state']       = db('routine_usage')->where('store_id', $this->us['store_id'])->where('stock_id', $value['id'])->value('status');
            }
        }
        
        r_date($custom, 200);
    }
    
    /**
     * 获取库存列表
     */
    public function CollectingStock_list_search(Common $common)
    {
        
        $request = Authority::param(['invname']);
        $data    = u8cInvcDetail(null, $this->us['store_id'], 1, 200, $request['invname'], 1, 0, null, $this->us['user_id'], 1);
        $data    = json_decode($data, true);

        if ($data['status'] == 'success') {
            $list = $data['data'];
            $invclcodes = array_column($list, 'invclcode');
            $pendingCounts  = $common->materialsPendingReview($this->us['store_id'], $invclcodes);
            // 2.3 循环赋值（仅内存操作，高效）
            foreach ($list as &$item) {
                $item['price'] = '*';
                // 恢复 nabnum 计算（使用批量查询的结果）
                $invclcode = $item['invclcode'] ?? '';
                $item['nabnum'] = bcsub(
                    $item['nabnum'] ?? 0,
                    $pendingCounts[$invclcode] ?? 0,
                    2
                );
                   $item['nabnums'] = $pendingCounts[$invclcode]??0;
            }
        } else {
            $list = null;
        }
        
        r_date($list, 200);
    }
    
      /**
     * 材料领用/借调待审核名单
     */
    public function listOfMaterialsAwaitingReview()
    {
        if ($this->us['Inventory'] == 0) {
            r_date(null, 200);
        }
        $store_id = $this->us['store_id'];
        $store_megre = db('store_megre', config('database.zong'))->order('id desc')->where('state', 1)->where('store_id', $store_id)->find();
        $storeIdList = $store_id;
        if (!empty($store_megre)) {
            $store_id = $store_megre['m_store_id'];
            $storeIdList = db('store_megre', config('database.zong'))->where('state', 1)->where('m_store_id', $store_id)->column('store_id');
        }

        $routine_usage  = db('secondment')
            ->whereIn('lender_store_id', $storeIdList)
            ->join('store', 'secondment.lender_store_id=store.store_id', 'left')
            ->where('secondment.status',  0)
            ->field('store.store_name username')
            ->select();

        $material_usage = db('material_usage')
            ->join('order', 'order.order_id=material_usage.order_id', 'left')
            ->join('user', 'order.assignor=user.user_id', 'left')
            ->join('store', 'order.store_id=store.store_id', 'left')
            ->where(['material_usage.types' => 2, 'material_usage.status' => 0])
            ->field('concat(user.username,"(",store.store_name,")") username,order.order_no')
            ->whereIn('order.store_id', $storeIdList)
            ->select();
        $statistics = [];
        foreach ($material_usage as $order) {
            $username = $order['username'];
            $orderNo = $order['order_no'];
            if (!isset($statistics[$username])) {
                $statistics[$username] = [];
            }
            // 用数组键去重，只保留唯一订单号
            $statistics[$username][$orderNo] = $orderNo;
        }
        $tong = [];
        // 最终数量取数组长度
        foreach ($statistics as $name => $orderNos) {
            $count = count($orderNos);
            // 拼接订单号列表（用分号+换行分隔）
            $orderList = implode(";\n", array_values($orderNos));
            // 组合完整的描述文本
            $listText = "{$name}:\n{$count}个材料领用未审核订单:\n{$orderList}";

            $tong[] = [
                'name' => $name,
                'title' => "待审核",
                'content' => $listText,
                'type' => 1,
                'count' => $count
            ];

            // 输出逻辑不变

        }
        $list = [];
        if (!empty($tong)) {

            $list = array_merge($list, $tong);
        }
        if (!empty($routine_usage)) {
            $routine_usage_list[] = [
                'name' => "外部借调",
                'title' => "待审核",
                'content' => '有'.count($routine_usage).'条材料借调待审核，请店铺管理人员，在店长APP审核',
                'type' => 2,
                'count' => count($routine_usage)
            ];
            $list = array_merge($list, $routine_usage_list);
        }
        r_date(empty($list)?null:$list, 200);
    }
    /**
     * 获取已选列表
     */
    public function get_Material_list()
    {
        $data = Request::instance()->post();
        //材料领用
        $material_usage = db('material_usage')->where(['order_id' => $data['order_id'], 'types' => $data['type']])->field('Material_id,material_name,type,square_quantity,total_price,company,unit_price,created_time,id,status,content as remake')->order('status asc')->select();
        if($data['type']==2){
            $secondment=\db('secondment')->join('routine_usage','routine_usage.id=secondment.debi_id','left')->join('store','store.store_id=secondment.lender_store_id','left')->where(['routine_usage.order_id' => $data['order_id'], 'secondment.category' => 2])->field('secondment.stock_name as material_name,secondment.number as square_quantity,secondment.latest_cost * secondment.number as total_price,secondment.company,secondment.latest_cost as unit_price,secondment.status,secondment.remake,secondment.id,store.store_name,secondment.created_time')->select();
            if(!empty( $secondment)){
                foreach($secondment as $k=>$item){
                    $secondment[$k]['type']=199;
                    if($item['status']==0){
                        $secondment[$k]['status']=1;
                    }
                    if($item['status']==3){
                        $secondment[$k]['status']=0; 
                    }
                   
                    
                    $secondment[$k]['id']=$item['id'];
                    // $secondment[$k]['total_price']=0;
                    $secondment[$k]['unit_price']=0;
                    $secondment[$k]['secondMethod']="借调[".$item['store_name']."]";
                    $secondment[$k]['Material_id']=0;
                }
            }
            $material_usage=array_merge($material_usage,$secondment);
        }
        
        r_date($material_usage, 200);
    }
    
    /**
     * 采购详情列表
     */
    public function get_routine_usage()
    {
        $params          = Authority::param(['invclcode']);
        $custom_material = [];
        $purchase_usage  = [];
        $routine_usage   = [];
        $custom_material = db('custom_material')->field('company,number,FROM_UNIXTIME(created_time,"%Y-%m-%d %H:%i") as created_time')->where(['store_id' => $this->us['store_id'], 'status' => 0])->where(['code' => $params['invclcode']])->select();
        
        $purchase_usage = db('purchase_usage')->field('company,number,FROM_UNIXTIME(created_time,"%Y-%m-%d %H:%i") as created_time,status,content')->where('type', 1)->where(['code' => $params['invclcode']])->where('store_id', $this->us['store_id'])->select();
        
        $routine_usage = db('routine_usage')->field('company,number,FROM_UNIXTIME(created_time,"%Y-%m-%d %H:%i") as created_time,status,content')->where(['code' => $params['invclcode'], 'store_id' => $this->us['store_id']])->where('types', 1)->select();
        
        $routine_cart = db('routine_cart')->field('measname as company,chooseNumber as number,original_number,FROM_UNIXTIME(created_time,"%Y-%m-%d %H:%i") as created_time,status,content,id')->where(['invclcode' => $params['invclcode'], 'store_id' => $this->us['store_id']])->select();

//        foreach ($routine_cart as $k => $list) {
//            $status = db('routine_usage')->where('id', $list['id'])->value('status');
//
//            if ($status == 2) {
//                $routine_cart[$k]['status'] = 2;
//            } elseif ($status == 0) {
//                $routine_cart[$k]['status'] = 0;
//            }
//        }
        $rows = array_merge($routine_cart, array_merge($routine_usage, array_merge($purchase_usage, $custom_material)));
        
        foreach ($rows as $k => $item) {
            if (isset($item['original_number']) && !empty($item['original_number'])) {
                $rows[$k]['original_number'] = $item['number'];
                $rows[$k]['number']          = $item['original_number'];
                
            } else {
                $rows[$k]['original_number'] = $item['number'];
            }
            
            
        }
        $rows = $this->arraySort($rows, 'created_time', SORT_DESC);
        r_date($rows, 200);
        
        
    }
    
    /**
     * 二维数组根据某个字段排序
     * @param array $array 要排序的数组
     * @param string $keys 要排序的键字段
     * @param string $sort 排序类型  SORT_ASC     SORT_DESC
     * @return array 排序后的数组
     */
    public function arraySort($array, $keys, $sort = SORT_DESC)
    {
        $keysValue = [];
        foreach ($array as $k => $v) {
            $keysValue[$k] = $v[$keys];
        }
        array_multisort($keysValue, $sort, $array);
        return $array;
    }
    
    /*
     * 领用详情
     */
    public function get_Collect()
    {
        $params = Authority::param(['invclcode']);
        
        $routine_usage = db('material_usage')
            ->field('IF(material_usage.types=1,user.username,app_user.username) as username,FROM_UNIXTIME(material_usage.created_time,"%Y-%m-%d %H:%i") as created_time,material_usage.id,material_usage.types,material_usage.square_quantity as number,material_usage.status,material_usage.company,material_usage.content')
            ->join(config('database.db2')['database'] . '.app_user', 'app_user.id=material_usage.user_id and material_usage.types=2', 'left')
            ->join('user', 'user.user_id=material_usage.user_id and material_usage.types=1', 'left')
            ->join('usage_record', 'usage_record.id=material_usage.id', 'left')
            ->join('user user1', 'material_usage.shopowner_id=user1.user_id', 'left')
            ->where(['user1.store_id' => $this->us['store_id']])
            ->where(['usage_record.unified' => $params['invclcode']])
            ->order('material_usage.id desc')
            ->select();
        
        
        r_date($routine_usage, 200);
    }
    
    /*
     * 店长采购详情
     */
    public function purchaseUsage()
    {
        $params = Request::instance()->get();
        db('message')->where(['order_id' => $params['id'], 'type' => 34, 'user_id' => $this->us['user_id']])->update([
            'already' => 0, 'have' => time(),
        ]);//
        //type1采购2领用
        $purchase_usage = db('purchase_usage')->where(['id' => $params['id']])->where('store_id', $this->us['store_id'])->order('id desc')->find();
        $num            = 0;
        $pr             = 0;
        
        if ($purchase_usage['status'] == 3) {
            $num += $purchase_usage['number'];
            $pr  += $purchase_usage['latest_cost'] * $purchase_usage['number'];
        }
        $purchase_usage['number'] = $purchase_usage['number'] + db('material_usage')->where('Material_id', $purchase_usage['id'])->where('type', 99)->whereIn('status', [0, 1])->sum('square_quantity');
        
        $purchase_usage['classification'] = 99;
        $data[]                           = $purchase_usage;
        $data                             = ['stock_name' => $purchase_usage['stock_name'], 'latest_cost' => $purchase_usage['latest_cost'], 'number' => $num, 'total_price' => sprintf('%.2f', $pr), 'data' => $data];
        r_date($data, 200);
    }
    
    /*
     * 自购采购详情
     */
    public function CollaborativeWarehouse()
    {
        $params = Request::instance()->get();
        
        //type1采购2领用
        $custom_material = db('custom_material')->where(['id' => $params['id']])->where('store_id', $this->us['store_id'])->order('id desc')->find();
        $num             = 0;
        $pr              = 0;
        $num             += $custom_material['number'];
        
        $pr                        += bcmul($custom_material['latest_cost'], $custom_material['number'],2);
        $custom_material['status'] = 3;
        $custom_material['number'] = $custom_material['number'] + db('material_usage')->where('Material_id', $custom_material['id'])->where('type', 0)->whereIn('status', [0, 1])->sum('square_quantity');
        $data[]                    = $custom_material;
        $data                      = ['stock_name' => $custom_material['stock_name'], 'latest_cost' => $custom_material['latest_cost'], 'number' => sprintf('%.2f', $num), 'total_price' => sprintf('%.2f', $pr), 'data' => $data];
        r_date($data, 200);
        
        
    }
    
    /**
     * 师傅材料审核
     */
    public function get_Material_To_examine(Common $common)
    {
        
        $data = Authority::param(['id', 'status', 'content']);
        $params = Request::instance()->post();
        if ($this->us['Inventory'] == 1) {
            r_date(null, 300, '库存盘点中，无法领用，请盘点完成后操作');
        }
       
        //师傅借调审核
        if(isset($params['type']) && $params['type']==199){
           $secondment=\db('secondment')->join('routine_usage','routine_usage.id=secondment.debi_id','left')->where(['secondment.id' => $data['id'], 'secondment.category' => 2])->field('secondment.lender_id,secondment.debi_id,routine_usage.order_id')->find();
            $orderList      = db('order')->where('order_id', $secondment['order_id'])->find();
            if (!empty($orderList['cleared_time'])) {
                r_date(null, 300, '该订单已结算');
            }
            if($data['status'] == 1){
                \db('secondment')->where(['secondment.id' => $data['id'], 'secondment.category' => 2])->update(['status'=>0]);
            }else{
                \db('secondment')->where(['secondment.id' => $data['id'], 'secondment.category' => 2])->update(['status'=>2, 'adopt' => time(), 'reviewer' => $this->us['user_id'], 'content' => $data['content']]);
                db('routine_usage')->where('id', $secondment['lender_id'])->update(['status' => 2, 'adopt' => time(), 'content' => $data['content']]);
                db('routine_usage')->where('id', $secondment['debi_id'])->update(['status' => 2, 'adopt' => time(), 'content' => $data['content']]);
            }
            r_date(null,200,'操作成功');
         
         }
         $material_usage = db('material_usage')->where(['id' => $data['id']])->find();
         $orderList      = db('order')->where('order_id', $material_usage['order_id'])->find();
         if (!empty($orderList['cleared_time'])) {
             r_date(null, 300, '该订单已结算');
         }
         //师傅正常领用材料审核
        db()->startTrans();
        try {
            
            $purchase_usage = db('usage_record')
                ->field('purchase_usage.code as purchase_usageId,custom_material.code as custom_materialId,routine_usage.code as routine_usageId,routine_cart.invclcode as routine_cartId')
                ->join('purchase_usage', 'purchase_usage.code=usage_record.unified and purchase_usage.store_id=' . $orderList['store_id'] . '', 'left')
                ->join('custom_material', 'custom_material.code=usage_record.unified and custom_material.store_id=' . $orderList['store_id'] . '', 'left')
                ->join('routine_usage', 'routine_usage.code=usage_record.unified and routine_usage.types=1 and routine_usage.store_id=' . $orderList['store_id'] . '', 'left')
                ->join('routine_cart', 'routine_cart.invclcode=usage_record.unified and routine_cart.store_id=' . $orderList['store_id'] . '', 'left')
                ->where('usage_record.classification', 0)
                ->where(['usage_record.id' => $data['id']])
                ->find();
            
            
            $code = $material_usage['code'];
            if ($purchase_usage) {
                if (!empty($purchase_usage['purchase_usageId'])) {
                    $code = $purchase_usage['purchase_usageId'];
                } elseif (!empty($purchase_usage['custom_materialId'])) {
                    $code = $purchase_usage['custom_materialId'];
                } elseif (!empty($purchase_usage['routine_usageId'])) {
                    $code = $purchase_usage['routine_usageId'];
                } elseif (!empty($purchase_usage['routine_cartId'])) {
                    $code = $purchase_usage['routine_cartId'];
                }
            }
            
            $unit_price = 0;
            if ($data['status'] == 1 && $material_usage['status'] != 1) {
                $op  = u8queryForStoreId($code, $orderList['store_id']);
                $u8c = json_decode($op, true);
                if ($u8c['status'] == 'success') {
                    $number = $u8c['data'];
                    if (!is_array($number)) {
                        $number = json_decode($u8c['data'], true);
                    }
                    if ($number['datas'][0]['nnum'] - $material_usage['square_quantity'] < 0) {
                        throw new Exception('库存不足');
                    } else {
                        $Leftover = $number['datas'][0]['nnum'] - $material_usage['square_quantity'];
                        
                        if ($Leftover >= 0) {
                            $inter    = u8insertU8c($orderList['store_id'], $material_usage['order_id'], $material_usage['square_quantity'], $code, 0, $data['id']);
                            $U8cinter = json_decode($inter, true);
                            if ($U8cinter['status'] != 'success') {
                                throw new Exception($U8cinter['errormsg']);
                            }
                            //材料成本售价
                            $materialCostSellingPrice = $U8cinter['data']['materialCostSellingPrice'];
                            // 材料成本单价
                            $materialCostUnitPrice = $U8cinter['data']['materialCostUnitPrice'];
                            $status     = $data['status'];
                            $total_price      =  bcmul($material_usage['square_quantity'] , $materialCostSellingPrice,2);
                            $total_profit      =  bcmul($material_usage['square_quantity'] , $materialCostUnitPrice,2);
                            //材料领用
                            db('material_usage')->where(['id' => $data['id']])->update(['status' => $status, 'content' => $data['content'], 'unit_price' => $materialCostSellingPrice, 'total_price' => $total_price, 'total_profit' => $total_profit, 'adopt' => time()]);
                        } else {
                            throw new Exception('库存不足');
                        }
                    }
                } else {
                    throw new Exception('请求异常，请稍后再试');
                }
                
            } else {
                $common->approvalReminder(['money' => $material_usage['total_price'], 'user_type' => $material_usage['types'], 'user_id' => $material_usage['user_id'], 'reject_user' => $this->us['username'], 'reject_desc' => $data['content'], 'approval_status' => $data['status'], 'approval_time' => time(), 'type' => 9, 'order_id' => $material_usage['order_id'], 'city_id' => config('cityId'), 'relation_id' => $data['id']]);
                db('material_usage')->where(['id' => $data['id']])->update(['status' => $data['status'], 'content' => $data['content'], 'adopt' => time()]);
            }
            
            db()->commit();
            $app_user = Db::connect(config('database.db2'))->table('app_user')->where('id', $material_usage['user_id'])->find();
            if (!empty($app_user['jpush_id'])) {
                $push = new Jpush();
                $push->master(['order_id' => $material_usage['order_id'], 'title' => '材料申请被店长', 'user_id' => $material_usage['user_id'], 'classification' => 5, 'jpush_id' => $app_user['jpush_id'], 'status' => $data['status']]);
            }
            r_date(null, 200);
        } catch (Exception $e) {
            db()->rollback();
            r_date(null, 300, $e->getMessage());
        }
        
    }
    
    /**
     * 获取费用已选列表
     */
    public function get_reimbursement_list(Capital $capital,OrderDeliveryManagerModel  $deliveryManagerModel)
    {
        $data = Request::instance()->post();
        if (!empty($data['user_id'])) {
            $this->us['user_id'] = $data['user_id'];
        }
        $IsStartupDelivere = $deliveryManagerModel->IsStartupDeliverer($data['order_id'], $this->us['user_id'], '');
        if (!empty($IsStartupDelivere)) {
            r_date(null, 300, '请接单后再操作');
        }
        //费用报销
        if ($data['type'] == 1) {
            $quer = db('reimbursement');
            if (isset($data['isMaterial'])) {
                $quer->where('classification', 4);
            } else {
                $quer->where('classification', '<>', 4)->where('reimbursement.type', 1);
            }
            if (isset($data['status'])) {
                if ($data['status'] == 0) {
                    $quer->where(function ($quer) {
                        $quer->where('reimbursement.status', 0)->whereOr('reimbursement.status', 3);
                    });
                } else {
                    $quer->where('reimbursement.status', $data['status']);
                }
                
            }
            
            $reimbursement = $quer->where(['reimbursement.order_id' => $data['order_id']])->join('user', 'user.user_id=reimbursement.user_id', 'left')->join('app_user', 'app_user.id=reimbursement.user_id', 'left')->field('reimbursement.reimbursement_name,reimbursement.id,reimbursement.money,reimbursement.voucher,reimbursement.created_time,reimbursement.status,reimbursement.remake, reimbursement.content as remarks,reimbursement.classification,reimbursement.payment_notes,reimbursement.secondary_classification,reimbursement.submission_time as submissionTime,if(reimbursement.type=1,user.username,app_user.username) as username,reimbursement.adopt,reimbursement.type,reimbursement.cleared_time')->select();
        } else {
            $exp  = new \think\db\Expression('field(reimbursement.status,0,3,1,2)');
            $quer = db('reimbursement');
            if (isset($data['isMaterial'])) {
                $quer->where('classification', 4);
            } else {
                $quer->where('classification', '<>', 4);
            }
            if (isset($data['status'])) {
                $quer->where('reimbursement.status', $data['status']);
            }
            $reimbursement = $quer->where(['reimbursement.order_id' => $data['order_id'], 'reimbursement.type' => 2])->join('app_user', 'app_user.id=reimbursement.user_id', 'left')->field('reimbursement.reimbursement_name,reimbursement.id,reimbursement.money,reimbursement.voucher,reimbursement.created_time,reimbursement.status,reimbursement.remake, reimbursement.content as remarks,reimbursement.classification,reimbursement.payment_notes,reimbursement.remake,reimbursement.secondary_classification,reimbursement.submission_time as submissionTime,app_user.username,reimbursement.adopt,reimbursement.type,reimbursement.cleared_time')->order($exp)->select();
        }
        foreach ($reimbursement as $k => $item) {
            $reimbursement[$k]['voucher'] = empty(unserialize($item['voucher'])) ? [] : unserialize($item['voucher']);
            $reimbursement_relation       = db('reimbursement_relation')
                ->Join('bank_card', 'bank_card.bank_id=reimbursement_relation.bank_id', 'left')
                ->field('bank_card.account_name as name,bank_card.bank_card_number as collection_number,capital_id,receipt_number')
                ->where('reimbursement_id', $item['id'])
                ->find();
            if ($item['classification'] != 4) {
                $type = 1;
            } else {
                $type = 2;
            }
            $reimbur = db('approval', config('database.zong'))->join('bi_user', 'bi_user.user_id=approval.nxt_id', 'left')->where('relation_id', $item['id'])->where('type', $type)->where('approval.city_id', config('cityId'))->value('bi_user.username');
            if ($item['type'] == 2 && empty($reimbur)) {
                $reimbursement[$k]['reviewedBy'] = $this->us['username'].' -[ 店长APP]';
            } else {
                $reimbursement[$k]['reviewedBy'] = !empty($reimbur) ? $reimbur.' -[ BI系统]' : null;
            }
            
            $reimbursement[$k]['submissionTime'] = !empty($item['submissionTime']) ? date('Y-m-d H:i', $item['submissionTime']) : null;
            $reimbursement[$k]['createdTime']    = !empty($item['created_time']) ? date('Y-m-d H:i', $item['created_time']) : null;
            $reimbursement[$k]['clearedTime']    = !empty($item['cleared_time']) ? date('Y-m-d H:i', $item['cleared_time']) : null;
            $reimbursement[$k]['adopt']          = !empty($item['adopt']) ? date('Y-m-d H:i', $item['adopt']) : null;
            
            $title                                = array_search($item['classification'], array_column($this->list_reimbursement_type(2), 'type'));
            $reimbursement[$k]['title_secondary'] = $this->list_reimbursement_type(2)[$title]['name'];
            if (!empty($item['secondary_classification'])) {
                $title_secondary                      = array_search($item['secondary_classification'], array_column($this->list_reimbursement_type(2), 'type'));
                $reimbursement[$k]['title_secondary'] = $reimbursement[$k]['title_secondary'] . '_' . $this->list_reimbursement_type(2)[$title_secondary]['name'];;
            }
            $reimbursement[$k]['receipt_number'] = isset($reimbursement_relation) ? $reimbursement_relation['receipt_number'] : '';
//            if ($reimbursement_relation['category'] == 1 && $reimbursement_relation['binding_uid'] == $this->us['user_id']) {
//                $reimbursement_relation['isMy'] = 1;
//            } else {
//                $reimbursement_relation['isMy'] = 0;
//            }
            if ($item['classification'] != 4) {
                $array = [];
                if (empty($reimbursement_relation)) {
                    $reimbursement_relation['name']              = '';
                    $reimbursement_relation['collection_number'] = '';
                } else {
                    if (!empty($reimbursement_relation['capital_id'])) {
                        $capitalList = $capital
                            ->with('SpecsList')
                            ->where(['types' => 1, 'enable' => 1, 'agency' => 0])
                            ->whereIn('capital_id', $reimbursement_relation['capital_id'])
                            ->select();
                        
                        foreach ($capitalList as $k1 => $item1) {
                            $array[$k1]['capital_id'] = $item1['capital_id'];
                            $array[$k1]['class_b']    = $item1['class_b'];
                            $array[$k1]['company']    = $item1['company'];
                            $array[$k1]['square']     = $item1['square'];
                            $array[$k1]['un_Price']   = $item1['un_Price'];
                            $array[$k1]['to_price']   = $item1['to_price'];
                            $array[$k1]['specsList']  = implode('/', array_column($item1['specs_list'], 'option_value_title'));
                        }
                    }
                    
                }
                $reimbursement[$k]['reimbursementList'] = $reimbursement_relation;
                $reimbursement[$k]['mainMaterialIds']   = $array;
            }
            
        }
        
        r_date($reimbursement, 200);
    }
    
    /*
       /*
    * 费用报销列表
    */
    public function approvedReimbursementQuantity()
    {
        $data         = Request::instance()->get();
        $data['type'] = 1;
        //费用报销
        if ($data['type'] == 1) {
            $quer          = db('reimbursement')
                ->where('classification', 4);
            $reimbursement = $quer->where(['reimbursement.order_id' => $data['order_id']])->field('sum(if(reimbursement.type=2 and (reimbursement.status=0 or reimbursement.status=3),1,0)) as count0,sum(if(reimbursement.type=1 and (reimbursement.status=0 or reimbursement.status=3),1,0)) as count1,sum(if(reimbursement.type=1 and reimbursement.status=1,1,0)) as count2,sum(if(reimbursement.type=1 and reimbursement.status=2,1,0)) as count3,sum(if(reimbursement.status=1,reimbursement.money,0)) as money')->select();
            
        } else {
            $exp           = new \think\db\Expression('field(reimbursement.status,0,3,1,2)');
            $quer          = db('reimbursement')
                ->where('classification', 4);
                $reimbursement = $quer->where(['reimbursement.order_id' => $data['order_id'], 'reimbursement.type' => 2])->field('sum(if(reimbursement.status=0 or reimbursement.status=3,1,0)) as count1,sum(if(reimbursement.status=1,1,0)) as count2,sum(if(reimbursement.status=2,1,0)) as count3,sum(if(reimbursement.status=1,reimbursement.money,0)) as money')->select();
        }
        $order_setting = db('order_setting')->where('order_id', $data['order_id'])->find();
        r_date(['count0' => !empty($reimbursement) ? $reimbursement[0]['count0'] : 0, 'count1' => !empty($reimbursement) ? $reimbursement[0]['count1'] : 0, 'count2' => !empty($reimbursement) ? $reimbursement[0]['count2'] : 0, 'count3' => !empty($reimbursement) ? $reimbursement[0]['count3'] : 0, 'money' => !empty($reimbursement) ? $reimbursement[0]['money'] : 0, 'isNewRequisition' => $order_setting['stop_agent_reimbursement']], 200);
    }
    
    /*
    
    /**
     * 师傅报销审核
     */
    public function get_Material_To_Reimbursement(Approval $approval, Common $common, OrderModel $orderModel)
    {
        $data = Request::instance()->post();
         //材料领用
            $reimbursement            = db('reimbursement')->where(['id' => $data['id']])->find();
            $orderList                = db('order')
                ->field('personal.num,order.cleared_time,order.settlement_time,order.deliverer')
                ->join('personal', 'order.tui_jian=personal.personal_id', 'left')
                ->join('contract', 'order.order_id=contract.orders_id', 'left')
                ->where('order.order_id', $reimbursement['order_id'])
                ->find();
            if ($orderList['deliverer'] != $this->us['user_id']) {
                r_date(null, 300, "请用该订单店长账号审核");
            }
        db()->startTrans();
        try {
           
            $cleared_time             = $orderList['cleared_time'];
            $order_setting            = db('order_setting')->where('order_id', $reimbursement['order_id'])->find();
            $orderList['isNeedPaper'] = $order_setting['payment_type'];
            $app_user                 = Db::connect(config('database.db2'))->table('app_user')->where('id', $reimbursement['user_id'])->find();
            $appUsername              = $app_user['username'];
            $io                          = explode(',', $reimbursement['capital_id']);
            $capital                     = db('capital')->whereIn('capital_id', $io)->field('class_b,to_price,company,(labor_cost+labor_cost_material) as labor_cost,labor_cost_reimbursement,capital_id,projectId')->select();
            $reimbursement_capital_beforehand                     = db('reimbursement_capital_beforehand')->where('delete_time',0)->whereIn('capital_id', $io)->sum('beforehand_money');
            $appUserOrderCapital        = db('app_user_order_capital')->whereIn('capital_id', $io)->whereNull('deleted_at')->field('sum(personal_price+cooperation_price) as  total_price')->select();
            $appUserOrderCapital                  = empty($appUserOrderCapital[0]['total_price']) ? 0 : $appUserOrderCapital[0]['total_price'];
            $order_times                = Db::table('order_times')->where('order_id', $reimbursement['order_id'])->field('change_work_time')->find();
            $mo=1;
            if ($data['status'] == 1) {
                if (($reimbursement['classification'] == 1 || $reimbursement['classification'] == 3) && ($order_times['change_work_time']<1720724400 && !in_array('10039',array_column($capital,'projectId')) && !in_array('10040',array_column($capital,'projectId'))|| $order_times['change_work_time']>1720724400) && $mo==0) {
                    //总得剩余额度
                    $money= (string)round(array_sum(array_column($capital,'labor_cost'))-array_sum(array_column($capital,'labor_cost_reimbursement'))-$reimbursement_capital_beforehand-$appUserOrderCapital,3);
                    if($money<$reimbursement['money']){
                        r_date(null,301,'师傅报销的金额，超出可报销范围' . (string)$money . '元，若仍然要报销，需要你在施工安排处给关联清单增加超限人工费');
                    }
                    $reimbursement_capital_beforehand = [];
                    foreach ($capital as $k => $item) {
                        $appUserOrderCapital        = db('app_user_order_capital')->where('capital_id', $item['capital_id'])->whereNull('deleted_at')->field('sum(personal_price+cooperation_price) as  total_price')->select();
                        $reimbursementCapitalBeforehand                     = db('reimbursement_capital_beforehand')->where('delete_time',0)->where('capital_id', $item['capital_id'])->sum('beforehand_money');
                        $appUserOrderCapital                  = empty($appUserOrderCapital[0]['total_price']) ? 0 : $appUserOrderCapital[0]['total_price'];
                        $dange               = (string)round($item['labor_cost']-$item['labor_cost_reimbursement']-$appUserOrderCapital-$reimbursementCapitalBeforehand,3);
                        $bi=(string)($dange/$money);
                        $beforehand_money = round($bi * $reimbursement['money'], 2);
                        if(($reimbursement['money']- (string)array_sum(array_column($reimbursement_capital_beforehand,'beforehand_money'))) <0){
                            $beforehand_money=0;
                            $last=$reimbursement['money'] - (string)array_sum(array_column($reimbursement_capital_beforehand, 'beforehand_money'));
                            $reimbursement_capital_beforehand[count($reimbursement_capital_beforehand)-1]['beforehand_money']=$reimbursement_capital_beforehand[count($reimbursement_capital_beforehand)-1]['beforehand_money']-abs($last);
                        }
                        if ($k != 0 && $k == count($capital) - 1  && ($reimbursement['money']- (string)array_sum(array_column($reimbursement_capital_beforehand,'beforehand_money'))) >0) {
                            $beforehand_money = $reimbursement['money'] - array_sum(array_column($reimbursement_capital_beforehand, 'beforehand_money'));
                        }
                        $reimbursement_capital_beforehand[] = ['capital_id' => $item['capital_id'], 'reimbursement_id' => $data['id'], 'beforehand_money' => $beforehand_money, 'create_time' => time()];
                    }
                    db('reimbursement_capital_beforehand')->insertAll($reimbursement_capital_beforehand);
                }
                $payment = $common::order_for_payment($reimbursement['order_id']);
                if ($reimbursement['classification'] != 4) {
                    if (!empty($cleared_time)) {
                        throw new Exception('该订单已结算');
                    }
                    $offer     = $orderModel->TuiNewOffer($reimbursement['order_id']);
                    $moneyList = db('reimbursement')->where('order_id', $reimbursement['order_id'])->where('status', '<>', 2)->where('id', '<>', $data['id'])->where('classification', '<>', 4)->sum('money');
                    if (!empty($order_setting)) {
                        if ($order_setting['max_reimbursement_rate'] == 0) {
                            if ($moneyList + $reimbursement['money'] > $payment[4] && $orderList['isNeedPaper'] == 1) {
                                throw new Exception('总报销金额'.($moneyList + $reimbursement['money']).'不能超出主合同收款金额' .  $payment[4] . '元，请在企业微信审批里提交“报销请款超限申请”');
                            }
                            if ($reimbursement['money'] > 100) {
                                if ($payment[0] / $offer['amount'] < 0.3) {
                                    throw new Exception('项目收款小于30%,无法使用报销,请严格按照收款制度进行收款');
                                }
                                
                            }
                        } elseif ($order_setting['max_reimbursement_rate'] > 0) {
                            if (round(($moneyList + $reimbursement['money']) / $offer['amount'] * 100, 2) >= $order_setting['max_reimbursement_rate']) {
                                throw new Exception('报销金额不能大于申请的' . $order_setting['max_reimbursement_rate'] . '%');
                            }
                        }
                    } else {
                        if ($moneyList + $reimbursement['money'] > $payment[4] && $orderList['isNeedPaper'] == 1) {
                            throw new Exception('报销金额不能大于收款金额');
                        }
                        if ($reimbursement['money'] > 100) {
                            if ($payment[0] / $offer['amount'] < 0.3) {
                                throw new Exception('项目收款小于30%,无法使用报销,请严格按照收款制度进行收款');
                            }
                            
                        }
                    }
                    
                    
                }
                if ($reimbursement['classification'] == 4) {
                    if (!empty($orderList['settlement_time'])) {
                        throw new Exception('该订单已结算');
                    }
                    $offer           = $orderModel->TotalProfit($reimbursement['order_id']);
                    $moneyListAgents = db('reimbursement')->where('order_id', $reimbursement['order_id'])->where('status', '<>', 2)->where('id', '<>', $data['id'])->where('classification', 4)->sum('money');
                    if (!empty($order_setting)) {
                        if ($order_setting['max_agent_reimbursement_rate'] == 0) {
                            if ($moneyListAgents + $reimbursement['money'] > $payment[5]) {
                                throw new Exception('报销金额不能大于收款金额');
                            }
                            if ($reimbursement['money'] > 100) {
                                if (bcdiv($payment[1], $offer['agencyMoney'], 2) < 0.49) {
                                    throw new Exception('主材收款小于50%，无法使用请款，请严格按照收款进度进行收款');
                                }
                                
                            }
                        } elseif ($order_setting['max_agent_reimbursement_rate'] > 0) {
                            if (round(($moneyListAgents + $reimbursement['money']) / $offer['agencyMoney'] * 100, 2) >= $order_setting['max_agent_reimbursement_rate']) {
                                throw new Exception('报销金额不能大于申请的' . $order_setting['max_agent_reimbursement_rate'] . '%');
                            }
                        }
                    } else {
                        if ($moneyListAgents + $reimbursement['money'] > $payment[5]) {
                            throw new Exception('报销金额不能大于收款金额');
                        }
                        if ($reimbursement['money'] > 100) {
                            if ($payment[1] / $offer['agencyMoney'] < 0.49) {
                                throw new Exception('主材收款小于50%，无法使用请款，请严格按照收款进度进行收款');
                            }
                            
                        }
                    }
                    
                }
                $title = array_search($reimbursement['classification'], array_column($this->list_reimbursement_type(2), 'type'));
                $title = '师傅' . $appUsername . $this->list_reimbursement_type(2)[$title]['name'] . '报销';
                $approval->Reimbursement($data['id'], $title, $this->us['username'], $reimbursement['classification']);
                $p = ['status' => 3, 'submission_time' => time()];
            } else {
                $p = ['status' => 2, 'remake' => isset($data['remake']) ? $data['remake'] : $data['reason'], 'submission_time' => time(),'adopt'=>time()];
                $common->approvalReminder(['money' => $reimbursement['money'], 'user_type' => $reimbursement['type'], 'user_id' => $reimbursement['user_id'], 'reject_user' => $this->us['username'], 'reject_desc' => isset($data['remake']) ? $data['remake'] : $data['reason'], 'approval_status' => 2, 'approval_time' => time(), 'type' => 1, 'order_id' => $reimbursement['order_id'], 'relation_id' => $data['id'], 'city_id' => config('cityId')]);
                $title = array_search($reimbursement['classification'], array_column($this->list_reimbursement_type(2), 'type'));
                $title = '师傅' . $appUsername . $this->list_reimbursement_type(2)[$title]['name'] . '报销';
            }
            db('reimbursement')->where(['id' => $data['id']])->update($p);
            db()->commit();
            if (!empty($app_user['jpush_id'])) {
                $push = new Jpush();
                $push->master(['order_id' => $reimbursement['order_id'], 'title' => $title, 'user_id' => $reimbursement['user_id'], 'classification' => $reimbursement['classification'], 'jpush_id' => $app_user['jpush_id'], 'status' => $p['status'],'remake'=> isset($data['remake']) ? $data['remake'] : $data['reason']]);
            }
            r_date(null, 200);
        } catch (Exception $e) {
            db()->rollback();
            r_date(null, 300, $e->getMessage());
        }
        
    }
    
    
    /*
     * 人工结算
     */
    public function artificial_list()
    {
        
        $data    = Request::instance()->post();
        $capital = $cap = db('capital')->where(['ordesr_id' => $data['order_id'], 'types' => 1, 'enable' => 1])->field('class_b,capital_id')->select();
        if (empty($capital)) {
            r_date(null, 300, '数据不存在');
        }
        foreach ($capital as $k => $kl) {
            $reality_artificial = Db::connect(config('database.db2'))->table('app_user_order_capital')->join('app_user', 'app_user.id=app_user_order_capital.user_id', 'left')->where('app_user_order_capital.capital_id', $kl['capital_id'])->whereNull('app_user_order_capital.deleted_at')->field('app_user_order_capital.work_time,app_user_order_capital.personal_price,app_user.username,app_user_order_capital.user_id')->select();
            //            echo Db::connect(config('database.db2'))->table('app_user_order_capital')->getLastSql();die;
            $capital[$k]['data'] = $reality_artificial;;
        }
        r_date($capital, 200);
    }
    
    /*
     * 人工结算师傅详情
     */
    public function artificialListMaster()
    {
        
        $data           = Request::instance()->post();
        $app_user_order = Db::connect(config('database.db2'))->table('app_user_order')
            ->join('app_user', 'app_user.id=app_user_order.user_id', 'left')
            ->where('app_user_order.order_id', $data['orderId'])
            ->whereNull('app_user_order.deleted_at')
            ->field('app_user.username,app_user_order.user_id as userId,FROM_UNIXTIME(app_user_order.created_at,"%Y-%m-%d %H:%i:%s")as createdTime,if(app_user_order.start_at !=0,FROM_UNIXTIME(app_user_order.start_at,"%Y-%m-%d %H:%i:%s"),"")as startAt,if(app_user_order.finish_at !=0,FROM_UNIXTIME(app_user_order.finish_at,"%Y-%m-%d %H:%i:%s"),"")as finishAt')
            ->select();
        $tageList       = null;
        if ($app_user_order) {
            foreach ($app_user_order as $k => $list) {
                $result[$list['username']] = $list;
            }
            foreach ($result as $k => $list) {
                $schemeTag['title'] = $k;
                $schemeTag['data']  = $result[$k];
                $tageList[]         = $schemeTag;
            }
        }
        
        r_date($tageList, 200);
    }
    
    /*
     * 人工结算师傅详情
     */
    public function MasterConstructionPlans()
    {
        
        $data                      = Request::instance()->post();
        $app_user_order_nodes_list = Db::connect(config('database.db2'))->table('app_user_order_node')
            ->field('app_user_order_node.resource_ids')
            ->where('app_user_order_node.order_id', $data['orderId'])
            ->where('app_user_order_node.user_id', $data['userId'])
            ->where('app_user_order_node.type', $data['type'])
            ->select();
        $pathId                    = implode(array_column($app_user_order_nodes_list, 'resource_ids'), ',');
        $path                      = Db::connect(config('database.db2'))->table('common_resource')->where('status', 1)->whereIn('id', $pathId)->field('mime_type,path,id')->select();
        $paths                     = [];
        foreach ($path as $k1 => $o) {
            $paths[] = 'https://images.yiniao.co/' . $o['path'];
        }
        r_date($paths, 200);
    }
    
    /*
     * 查公司
     */
    public function u8c_corp()
    {
        $request            = Authority::param(['pk_corp']);
        $reality_artificial = Db::connect(config('database.zong'))->table('u8c_corp')->where('pk_corp', $request['pk_corp'])->field('fathercorp,innercode,pk_corp as pkCorp,store_id as storeId,unitcode,unitname,unitshortname')->find();
        
        r_date($reality_artificial, 200);
        
    }
    
    
    /*
     * 采购添加
     */
    public function purchase_usage_material(Approval $approval)
    {
        
        $data = Request::instance()->post();
        db()->startTrans();
        try {
            $validate = new validate\Purchase_usage();
            if (!$validate->check($data)) {
                r_date($validate->getError(), 300);
            }
            $t1    = microtime(true);
            $t2    = microtime(true);
            $l     = ($t2 - $t1) * 1000;
            $sp_no = substr(date('YmdHis') . $l, 0, 14);
            $id    = db('purchase_usage')->insertGetId(['stock_name' => $data['stock_name'], 'company' => $data['company'], 'latest_cost' => $data['latest_cost'], 'voucher' => !empty(json_decode($data['voucher'], true)) ? serialize(json_decode($data['voucher'], true)) : '', 'sp_no' => $sp_no, 'user_id' => $this->us['user_id'], 'store_id' => $this->us['store_id'], 'created_time' => time(), 'remake' => $data['remake'], 'type' => 1, 'number' => $data['number'], 'meas' => $data['meas'], 'invcl' => $data['invcl'], 'invcl_name' => $data['invcl_name'], 'status' => 0, 'order_id' => $data['order_id'], 'address' => $data['address'], 'name' => $data['name'], 'phone' => $data['phone']]);
            $title = $this->us['username'] . '材料采购';
            
            db()->commit();
            $approval->Purchase($id, $title, $this->us['username'], 1, $this->us['user_id']);
            
            r_date(null, 200);
        } catch (Exception $e) {
            db()->rollback();
            r_date(null, 300, $e->getMessage());
        }
        
        
    }
    
    /*
    * 采购收货/入库
    */
    public function purchase_usage_Warehousing()
    {
        $data = Request::instance()->post();
        //入库
        $id = db('purchase_usage')->where('id', $data['id'])->update(['status' => 3, 'notes' => $data['notes'], 'notes_voucher' => !empty($data['img']) ? serialize(json_decode($data['img'], true)) : '']);
        if ($id) {
            r_date($id, 200);
        } else {
            r_date(null, 300);
        }
        
    }
    
    /*
    * 常规材料/入库
    */
    public function routine_usage_Warehousing()
    {
        $data = Request::instance()->post();
        db::startTrans();
        try {
            $routine_usage = db('routine_usage')->where('id', $data['id'])->find();
            
            if ($routine_usage['secondment'] == 1) {
                $secondment = \db('secondment')->where('debi_id', $routine_usage['id'])->find();
                
                db('routine_usage')->where('created_time', $secondment['created_time'])->where('stock_id', $secondment['stock_id'])->where(['store_id' => $secondment['lender_store_id']])->update(['storage_time' => time(), 'status' => 3]);
                db('routine_usage')->where('created_time', $secondment['created_time'])->where('stock_id', $secondment['stock_id'])->where(['store_id' => $secondment['debi_store_id']])->update(['status' => 3, 'notes' => $data['notes'], 'storage_time' => time(), 'voucher' => !empty($data['img']) ? serialize(json_decode($data['img'], true)) : '']);
                
                
                db('secondment')->where('created_time', $secondment['created_time'])->where('stock_id', $secondment['stock_id'])->where(['lender_store_id' => $secondment['lender_store_id']])->update(['status' => 3]);
                
            } else {
                //入库
                db('routine_usage')->where('id', $data['id'])->update(['status' => 3, 'notes' => $data['notes'], 'storage_time' => time(), 'voucher' => !empty($data['img']) ? serialize(json_decode($data['img'], true)) : '']);
            }
            db::commit();
            r_date(null, 200);
        } catch (Exception $exception) {
            db::rollback();
            r_date(null, 300, $exception->getMessage());
        }
    }
    
    //    /*
    //         * 常规材料直接入库没有收货
    //         */
    //    public function routine_usage_Warehousing()
    //    {
    //        $data = Request::instance()->post();
    //        //入库
    //        $custom = db('stock')
    //            ->where('id', $data['id'])
    //            ->find();
    //
    //        if (empty($custom)) {
    //            r_date(null, 300, '数据不存在');
    //        }
    //        $id = db('routine_usage')->insertGetId([
    //            'stock_name'   => $custom['stock_name'],
    //            'stock_id'     => $custom['id'],
    //            'store_id'     => $this->us['store_id'],
    //            'company'      => $custom['company'],
    //            'latest_cost'  => $custom['latest_cost'],
    //            'user_id'      => $this->us['user_id'],
    //            'number'       => $data['number'],
    //            'status'       => 0,
    //            'created_time' => time(),
    //        ]);
    //        if ($id) {
    //            r_date($id, 200);
    //        } else {
    //            r_date(null, 400);
    //        }
    //    }
    /*
      * 常规材料直接入库没有收货
      */
    public function routine_Warehousing(Approval $approval)
    {
        $data = Request::instance()->post();
        
        db()->startTrans();
        try {
            
            
            $t1    = microtime(true);
            $t2    = microtime(true);
            $l     = ($t2 - $t1) * 1000;
            $sp_no = substr(date('YmdHis') . $l, 0, 14);
            
            $id = db('routine_usage')->insertGetId(['store_id' => $this->us['store_id'], 'stock_name' => '材料库存增加', 'user_id' => $this->us['user_id'], 'company' => '', 'status' => 0, 'voucher' => '', 'created_time' => time(), 'types' => 2, 'remake' => $data['remake'], 'sp_no' => $sp_no, 'address' => $data['address'], 'phone' => $data['phone'], 'name' => $data['name'], 'order_id' => $data['order_id']]);
            
            db('routine_cart')->insertGetId(['id' => $id, 'invname' => $data['invname'], 'measname' => $data['measname'], 'invclcode' => $data['invclcode'], 'chooseNumber' => $data['number'], 'created_time' => time(), 'store_id' => $this->us['store_id']]);
            
            $title = $this->us['username'] . '材料采购';
            db()->commit();
            $approval->Purchase($id, $title, $this->us['username'], 2, $this->us['user_id']);
            r_date(null, 200);
        } catch (Exception $e) {
            db()->rollback();
            r_date(null, 300, $e->getMessage());
        }
    }
    
    public function list_reimbursement_type($type = 1, $id = 1)
    {
        
        
        if ($type == 1) {
            if ($id == 0) {
                $data    = [
                    ['name' => '建渣打拆', 'type' => 1],
                    ['name' => '小材料(不报销主材)', 'type' => 2, 'data' => [
                        ['type' => 8, 'name' => '泥工辅材'],
                        ['type' => 9, 'name' => '木工及墙板材料'],
                        ['type' => 10, 'name' => '水电工材料'],
                        ['type' => 11, 'name' => '油漆工材料'],
                        ['type' => 12, 'name' => '小耗材及小工具'],
                        ['type' => 13, 'name' => '小主材'],
                    ]],
                    ['name' => '协作人工', 'type' => 3],
                    ['type' => 7, 'name' => '运费'],
                    // ['type' => 9, 'name' => '直售报销'],
                ];
                $valuess = \db('sys_config', config('database.zong'))->where('keyss', 'cooperation_reimbursement')->value('valuess');
                foreach ($data as $k => $item) {
                    if ($item['type'] == 3 && $valuess == 0) {
                        unset($data[$k]);
                    }
                }
                
            } else {
                $data = [['name' => '返工材料成本', 'type' => 4], ['name' => '返工人工成本', 'type' => 5,], ['name' => '返工其他费用', 'type' => 6]];
            }
            
            r_date(array_merge($data), 200);
        } else {
            $approval = new Approval();
            return $approval->listReimbursement();
        }
        
    }
    
    public function MaterialList(OrderModel $orderModel, $order_startDate, $order_endDate, $type, $page, $limit = 20)
    {
        
        $material_usage = db('material_usage');
        $condition      = [];
        $secondmentcondition      = [];
        if (!empty($order_startDate) && !empty($order_endDate)) {
            
            $start                     = strtotime($order_startDate . ' 00:00:00');
            $end                       = strtotime($order_endDate . ' 23:59:59');
            $condition['created_time'] = ['between', [$start, $end]];
            $secondmentcondition['secondment.created_time'] = ['between', [$start, $end]];
        }
        
        if (!empty($type) && $type == 3) {
            $condition['status'] = 0;
            $secondmentcondition['secondment.status'] = 3;
            $condition['types']  = 2;
        }
        $article = $material_usage->where('shopowner_id', $this->us['user_id'])->distinct('order_id')->where('code', '<>', 0)->whereNotNull('code')->where($condition)->field('order_id')->order('created_time desc')->page($page, $limit)->select(); 
        $secondment=\db('secondment')->join('routine_usage','routine_usage.id=secondment.debi_id','left')->join('order','order.order_id=routine_usage.order_id','left')->join('store','store.store_id=secondment.lender_store_id','left')->where(['order.deliverer' => $this->us['user_id'], 'secondment.category' => 2])->where($secondmentcondition)->field('secondment.stock_name as material_name,secondment.number as square_quantity,secondment.latest_cost * secondment.number as total_price,secondment.company,secondment.latest_cost as unit_price,secondment.status,secondment.id,secondment.debi as user_id,secondment.created_time,routine_usage.order_id,store.store_name')->select();
        if(!empty($secondment)){
            $orderIdList=[];
           foreach($secondment as $k=>$item){
            $orderIdList[]=['order_id'=>$item['order_id']];
                $secondment[$k]['type']=199;
                $secondment[$k]['types']=2;
                if($item['status']==0){
                    $secondment[$k]['status']=1;
                }
                if($item['status']==3){
                    $secondment[$k]['status']=0; 
                }
                $secondment[$k]['id']=$item['id'];
                $secondment[$k]['secondMethod']="借调[".$item['store_name']."]";
               
            }
            $articleOrderId=array_merge($article,$orderIdList);
            $result = [];
            $orderIds = [];
    
            foreach ($articleOrderId as $item) {
                $orderId = $item['order_id'];
                if (!in_array($orderId, $orderIds)) {
                    $result[] = ['order_id'=>$item['order_id']];
                    $orderIds[] = $orderId;
                }
            }
            $article=array_merge($result);
        }
       
        $data    = [];
        foreach ($article as $k => $item) {
            $data[$k]['order_id'] = $item['order_id'];
            $data[$k]['address']  = $orderModel->addres($item['order_id']);
            $secondmentList=[];
            foreach ($secondment as  $value1) {
                if($item['order_id']==$value1['order_id']){
                    $secondmentList[]=$value1;
                }
            }
            
            $list                 = db('material_usage')->where('order_id', $item['order_id'])->where('code', '<>', 0)->whereNotNull('code')->where($condition)->field('material_name,square_quantity,unit_price,user_id,types,type,total_price,status,types,id,content')->select();
            if(!empty($secondmentList)){
                
                $list =array_merge($list,$secondmentList);
               
            }
           foreach ($list as $value) {
                if ($value['types'] == 2) {
                    $value['username'] = Db::connect(config('database.db2'))->table('app_user')->where('id', $value['user_id'])->find()['username'];
                } else {
                    $value['username'] = $this->us['username'];
                } 
                $data[$k]['data'][] = $value;
            }
        }
        
        r_date($data, 200);
        
    }
    
    public function ReimbursementList(OrderModel $orderModel, $order_startDate, $order_endDate, $type, $page, $limit = 1)
    {
        $isMaterial    = Request::instance()->get();
        $reimbursement = db('reimbursement');
        $condition     = [];
        if (!empty($order_startDate) && !empty($order_endDate)) {
            
            $start                     = strtotime($order_startDate . ' 00:00:00');
            $end                       = strtotime($order_endDate . ' 23:59:59');
            $condition['created_time'] = ['between', [$start, $end]];
        }
        if (!empty($type) && $type == 4) {
            $condition['reimbursement.status'] = 0;
            $condition['reimbursement.type']   = 2;
        }
        $quer = $reimbursement;
        if (isset($isMaterial['isMaterial'])) {
            
            $quer->where('reimbursement.classification', 4);
        } else {
            
            $quer->where('reimbursement.classification', '<>', 4);
        }
        $list = $quer->where('reimbursement.shopowner_id', $this->us['user_id'])->join('app_user','app_user.id=reimbursement.user_id','left')
        ->where($condition)
        ->field('reimbursement.id, reimbursement.order_id, reimbursement.reimbursement_name, reimbursement.money, reimbursement.status, reimbursement.classification, IF(reimbursement.type = 2, app_user.username, "'.$this->us['username'].'") as username,reimbursement.type')
        ->order('reimbursement.created_time desc')
        ->page($page, $limit)->select();
         $result = [];
        $orderIds = [];

        foreach ($list as $item) {
            $orderId = $item['order_id'];
            if (!in_array($orderId, $orderIds)) {
                $result[] = $item;
                $orderIds[] = $orderId;
            }
        }
        $data = [];
        foreach ($result as $k=> $item) {
            $data[$k]['order_id'] = $item['order_id'];
            $data[$k]['address']  = $orderModel->addres($item['order_id']);
            foreach($list as  $l=>$value){
                if($value['order_id']==$item['order_id']){
                    if (!empty($value['cleared_time'])) {
                        $value['status'] = 4;
                    }
                    if ($value['classification'] != 4) {
                        $type = 1;
                    } else {
                        $type = 2;
                    }
                    $reimbur = db('approval', config('database.zong'))->join('bi_user', 'bi_user.user_id=approval.nxt_id', 'left')->where('relation_id', $value['id'])->where('type', $type)->where('approval.city_id', config('cityId'))->value('bi_user.username');
                    if ($reimbur) {
                        if ($value['status'] != 2) {
                            if ($value['status'] != 1) {
                                $value['reimbursement_name'] = $value['reimbursement_name'] . "\n" . '【当前审批人:' . $reimbur . '】';
                            }
                            
                        } else {
                            $value['reimbursement_name'] = $value['reimbursement_name'] . "\n" . '【当前拒绝人:' . $reimbur . '】';
                        }
                    }
                    $title          = array_search($value['classification'], array_column($this->list_reimbursement_type(2), 'type'));
                    $value['title'] = $this->list_reimbursement_type(2)[$title]['name'];
                    unset($value['classification']);
                    $data[$k]['data'][] = $value;
                }
            }
           }

        r_date(array_values($data), 200);
    }
    
    /*
     * 报销详情
     */
    
    public function ReimbursementInfo($id)
    {
        
        $reimbursement = db('reimbursement')
            ->where('id', $id)->find();
        if ($reimbursement['type'] == 2) {
            $reimbursement['username'] = Db::connect(config('database.db2'))->table('app_user')->where('id', $reimbursement['user_id'])->find()['username'];
        } else {
            $reimbursement['username'] = $this->us['username'];
        }
        
        
        if ($reimbursement['classification'] == 4) {
            $type = 2;
        } else {
            $type = 1;
        }
        $relation = db('reimbursement_relation')
            ->join('agency', 'agency.agency_id=reimbursement_relation.bank_id', 'left')
            ->join('reimbursement', 'reimbursement.id=reimbursement_relation.reimbursement_id', 'left')
            ->join('bank_card', 'bank_card.bank_id=reimbursement_relation.bank_id', 'left')
            ->join('capital', 'FIND_IN_SET(capital.capital_id, replace(reimbursement_relation.capital_id," ",""))', 'left')
            ->where(['reimbursement_relation.reimbursement_id' => $reimbursement['id']])
            ->field('if(reimbursement.classification=4,CONCAT("账户：(",agency.collection_name,")"),CONCAT("账户：(",bank_card.account_name,")")) as collection_name,if(reimbursement.classification=4,CONCAT("帐号：(",if(LENGTH(agency.collection_number)<8,REPLACE(agency.collection_number,SUBSTR(agency.collection_number FROM 5 ),"****"),REPLACE(agency.collection_number,SUBSTR(agency.collection_number FROM 5 FOR 12),"****") ),")"),CONCAT("帐号：(",if(LENGTH(bank_card.bank_card_number)<8,REPLACE(bank_card.bank_card_number,SUBSTR(bank_card.bank_card_number FROM 5 ),"****"),REPLACE(bank_card.bank_card_number,SUBSTR(bank_card.bank_card_number FROM 5 FOR 12),"****") ),")")) as collection_number,if(reimbursement.classification=4,CONCAT("开户行：(",agency.bank_of_deposit,")"),CONCAT("银行：(",bank_card.bank_of_deposit,")")) as deposit,if(reimbursement.classification=4,agency.agency_name," ") as agencyName,capital.class_b,CONCAT(capital.un_Price,"/元") as un_Price,CONCAT(capital.square,"/",capital.company) as square,CONCAT(capital.to_price,"/元") as toPrice,capital.capital_id,reimbursement_relation.receipt_number,reimbursement.classification,reimbursement_relation.bank_id')
            ->select();
        if (!empty($relation)) {
            $capital_value = db('capital_value')->whereIn('capital_id', array_column($relation, 'capital_id'))->select();
            foreach ($relation as $k => $item) {
                foreach ($capital_value as $list) {
                    if ($item['capital_id'] == $list['capital_id']) {
                        $relation[$k]['capitalValue'][] = $list['title'];
                    }
                }
            }
            foreach ($relation as $k => $item) {
                $relation[$k]['capitalValue'] = !empty($item['capitalValue']) ? implode('/', $item['capitalValue']) : '';
                if ($item['classification'] == 4) {
                    $agency                            = db('agency', config('database.zong'))->where('agency_id', $item['bank_id'])->field('CONCAT("账户：(",agency.collection_name,")") as collection_name,CONCAT("帐号：(",if(LENGTH(agency.collection_number)<8,REPLACE(agency.collection_number,SUBSTR(agency.collection_number FROM 5 ),"****"),REPLACE(agency.collection_number,SUBSTR(agency.collection_number FROM 5 FOR 12),"****") ),")") as collection_number,CONCAT("开户行：(",agency.bank_of_deposit,")") as deposit,agency.agency_name as agencyName')->find();
                    $relation[$k]['collection_name']   = $agency['collection_name'];
                    $relation[$k]['agencyName']        = $agency['agencyName'];
                    $relation[$k]['collection_number'] = $agency['collection_number'];
                    $relation[$k]['deposit']           = $agency['deposit'];
                }
            }
        }
        
        
        $reimbursementApproval       = db('approval', config('database.zong'))
            ->join('bi_user', 'FIND_IN_SET(bi_user.user_id, replace(approval.approved_by," ",""))', 'left')
            ->where('approval.relation_id', $id)
            ->where('type', $type)
            ->where('approval.city_id', config('cityId'))
            ->field('bi_user.username,bi_user.user_id,approval.nxt_id,approval.approval_id')
            ->select();
        $filterReimbursementApproval = [];
        if (!empty($reimbursementApproval)) {
            
            $approval_schedule = db('approval_schedule', config('database.zong'))->where('approval_id', $reimbursementApproval[0]['approval_id'])->select();
            
            foreach ($reimbursementApproval as $k => $item1) {
                foreach ($approval_schedule as $list1) {
                    if ($item1['user_id'] == $list1['user_id']) {
                        $filterReimbursementApproval[$k]['state']          = $list1['approval_status'];
                        $filterReimbursementApproval[$k]['approvalUpdate'] = !empty($list1['update_time']) ? date('Y-m-d H:i', $list1['update_time']) : '';
                        $filterReimbursementApproval[$k]['username']       = $item1['username'];
                        $filterReimbursementApproval[$k]['remake']         = $list1['remarks'];
                    }
                    
                }
            }
            
        }
        
        $title = array_search($reimbursement['classification'], array_column($this->list_reimbursement_type(2), 'type'));
        if (!empty($reimbursement['secondary_classification'])) {
            $title2                           = array_search($reimbursement['secondary_classification'], array_column($this->list_reimbursement_type(2), 'type'));
            $reimbursement['title_secondary'] = '_' . $this->list_reimbursement_type(2)[$title2]['name'];
        } else {
            $reimbursement['title_secondary'] = '';
        }
        
        $reimbursement['title_secondary']             = $this->list_reimbursement_type(2)[$title]['name'] . $reimbursement['title_secondary'];
        $reimbursement['relation']                    = $relation;
        $reimbursement['filterReimbursementApproval'] = $filterReimbursementApproval;
        $reimbursement['created_time']                = !empty($reimbursement['created_time']) ? date('Y-m-d H:i', $reimbursement['created_time']) : '';
        $reimbursement['adopt']                       = !empty($reimbursement['adopt']) ? date('Y-m-d H:i', $reimbursement['adopt']) : '';
        $reimbursement['cleared_time']                = !empty($reimbursement['cleared_time']) ? date('Y-m-d H:i', $reimbursement['cleared_time']) : '';//计算时间
        $reimbursement['voucher']                     = !empty($reimbursement['voucher']) ? unserialize($reimbursement['voucher']) : null;
        if ($reimbursement['type'] == 1 && $reimbursement['status'] == 0) {
            $reimbursement['status'] = 1;
        }
        r_date($reimbursement, 200);
        
    }
    
    /*
     * 审核列表条数
     */
    public function ListSummary()
    {
        
        $data['reimbursementMoney'] = sprintf("%.2f", db('reimbursement')->where('shopowner_id', $this->us['user_id'])->where('classification', '<>', 4)->where('status', 1)->whereNull('cleared_time')->sum('money'));//订单费用报销
        //个人中心店长材料审核列表
        $material_usage = db('material_usage')->where('shopowner_id', $this->us['user_id'])->where('code', '<>', 0)->whereNotNull('code')->where('status', 0)->count();
        //待审批的材料借调数量
        $secondment=\db('secondment')->join('routine_usage','routine_usage.id=secondment.debi_id','left')->join('order','order.order_id=routine_usage.order_id','left')->join('store','store.store_id=secondment.lender_store_id','left')->where(['order.assignor' => $this->us['user_id'], 'secondment.category' => 2,'secondment.status' => 3])->count();
        $data['materialUsageCount']= $material_usage+$secondment;
        $data['reimbursementCount'] = db('reimbursement')->where('shopowner_id', $this->us['user_id'])->where('classification', '<>', 4)->where('type', 2)->where('status', 0)->count();
        $data['MaterialCount']      = sprintf("%.2f", db('reimbursement')->where('shopowner_id', $this->us['user_id'])->where('classification', 4)->where('status', 1)->sum('money'));
        $data['routineUusageCount'] = db('secondment')->where('lender_store_id', $this->us['store_id'])->whereNotNull('code')->where('code', '<>', 0)->where('status', 0)->count();
        if($this->us['reserve']==2){
            $data['routineUusageCount']=0;
        } 
        //上下道工序审核
        $data['previousAcceptance'] = \db('app_user_previous_acceptance')->join('order', 'order.order_id=app_user_previous_acceptance.order_id')->where('app_user_previous_acceptance.standard', '<>',1)->where('app_user_previous_acceptance.state', 3)->where('order.deliverer', $this->us['user_id'])->count();
        r_date($data, 200);
    }
    /**
     * 
     * //上下道工序审核列表
     * 
     */
    public function previousAcceptanceList()
    {
        $isMaterial    = Request::instance()->get();
        $quer = db('app_user_previous_acceptance')
            ->join('order', 'order.order_id=app_user_previous_acceptance.order_id');
        $condition     = [];
        if (!empty($order_startDate) && !empty($order_endDate)) {

            $start                     = strtotime($order_startDate . ' 00:00:00');
            $end                       = strtotime($order_endDate . ' 23:59:59');
            $condition['created_time'] = ['between', [$start, $end]];
        }
        if (isset($isMaterial['orderId']) && $isMaterial['orderId'] != 0) {

            $quer->where('app_user_previous_acceptance.order_id', $isMaterial['orderId']);
        }
        if (isset($isMaterial['type'])) {
            $condition['app_user_previous_acceptance.state'] = ['<>', 3];
            if ($isMaterial['type'] == 0) {
                $condition['app_user_previous_acceptance.state'] = 3;
            }
        }
        $list = $quer->where('order.deliverer', $this->us['user_id'])->whereNotNull('app_user_previous_acceptance.work_process_id')->join('app_user', 'app_user.id=app_user_previous_acceptance.app_user_id', 'left')
            ->where($condition)
             ->where('app_user_previous_acceptance.standard','<>',1)
            ->field('app_user_previous_acceptance.id, app_user_previous_acceptance.order_id, app_user_previous_acceptance.work_time,app_user_previous_acceptance.creation_time,app_user.username,app_user_previous_acceptance.standard,app_user_previous_acceptance.price,app_user_previous_acceptance.state,app_user_previous_acceptance.to_price')
            ->order('app_user_previous_acceptance.creation_time desc')
            
            ->select();



        $data = [];
        foreach ($list as $k => $item) {
            $data[$k]['order_id'] = $item['order_id'];
            $data[$k]['id'] = $item['id'];
            $data[$k]['createdTime']=date('Y-m-d H:i:s',$item['creation_time']);

            $title = '';
            if ($item['standard'] == 2) {
                $title = '有影响-需要我自己处理';
            }
            if ($item['standard'] == 3) {
                $title = '有影响-今日无法施工';
            }
            $state = $item['state'];
            $condition='';
            if($state==0){
                $condition='驳回-->';
            }

            $data[$k]['title']  = $item['username'] . '师傅，在上下道工序验收时，标记了' . $title;
            $data[$k]['toPrice']  = $item['to_price'];
            if($item['to_price']==0){
                $data[$k]['toPrice']  = bcmul($item['price'],$item['work_time'],2);
            }
            
            $data[$k]['content']  = $condition.'需要增加【' . $item['work_time'] . '工时，约'.$data[$k]['toPrice'].'元工费】';
            //0不通过1通过3待审核、
           
           

            $data[$k]['state']  = $state;
        }

        r_date($data, 200);
    }
    /**
     * 
     * 上下道工序审核
     * 
     */
    public function previousAcceptanceExamine()
    {
        $isMaterial    = Request::instance()->get();


        $date['audit_remarks'] = $isMaterial['remarks'] ?? "";
        $date['user_id'] = $isMaterial['userId'] ?? 0;
        $date['to_price'] = $isMaterial['toPrice'] ?? 0;
        $date['state'] = $isMaterial['state'];
        db('app_user_previous_acceptance')
            ->where('app_user_previous_acceptance.id', $isMaterial['id'])
            ->update($date);
        if ($date['state'] == 1) {
            $app_user_previous_acceptance = db('app_user_previous_acceptance')
                ->where('app_user_previous_acceptance.id', $isMaterial['id'])
                ->find();
            $app_user = db('app_user')
                ->where('id', $date['user_id'])
                ->find();
            $user_type = 2;
            if ($app_user['assist'] == 1) {
                $user_type = 8;
            }
             $order=db('order')
            ->where('order_id', $app_user_previous_acceptance['order_id'])
            ->find();
             $order_times=db('order_times')
            ->where('order_id', $app_user_previous_acceptance['order_id'])
            ->find();
            db('approval_schedule_liability', config('database.zong'))->insert(['order_id' => $app_user_previous_acceptance['order_id'], 'user_id' => $date['user_id'], 'user_type' => $user_type, 'user_name' => $app_user['username'], 'user_mobile' => $app_user['mobile'], 'money' => $date['to_price'], 'money_type' => 2, 'money_notes' => $date['audit_remarks'], 'create_time' => time()]);
            //师傅行为扣分
             db('scan_evaluation_score', config('database.zong'))->insert(['order_id' => $app_user_previous_acceptance['order_id'], 'user_id' => $date['user_id'], 'user_type' => 2, 'types' => 8, 'user_phone' => $app_user['mobile'], 'relation_id' => $isMaterial['id'], 'score' => '-3', 'city_id' => config('cityId'), 'create_time' => time(),'score_time'=>time(),'store_id'=>$order['store_id'],'channel_id'=>$order['channel_id'],'channel_details'=>$order['channel_details'],'pro_id'=>$order['pro_id'],'pro_id1'=>$order['pro_id1'],'pro_id2'=>$order['pro_id2'],'con_time'=>$order_times['signing_time'],'change_work_time'=>$order_times['change_work_time'],'business_id'=>$order['business_id'],'content'=>$order['order_no']]);
        }

        r_date(null, 200);
    }
       /**
     * 
     * 上下道工序审核详情
     * 
     */
    public function previousAcceptanceInfo()
    {
        
        $isMaterial    = Request::instance()->get();
        $list = db('app_user_previous_acceptance')
         ->where('app_user_previous_acceptance.id', $isMaterial['id'])->join('app_user', 'app_user.id=app_user_previous_acceptance.app_user_id', 'left')->join('app_user appUser', 'appUser.id=app_user_previous_acceptance.user_id', 'left')
         ->field('app_user_previous_acceptance.id, app_user_previous_acceptance.order_id, app_user_previous_acceptance.work_time,app_user_previous_acceptance.creation_time,app_user.username,app_user_previous_acceptance.standard,app_user_previous_acceptance.imgs,app_user_previous_acceptance.remarks,app_user_previous_acceptance.audit_remarks,app_user_previous_acceptance.price,app_user_previous_acceptance.work_type,app_user_previous_acceptance.state,app_user_previous_acceptance.work_process_id,appUser.username as fineUserName,app_user_previous_acceptance.user_id,app_user_previous_acceptance.to_price')
        ->find();

        $data['title']='上下道工序验收不合格';
        //0不通过1通过3待审核、
            $state = $list['state'];
            if ($list['state'] == 0) {
                $state = 0;
            }
        $data['state']=$state;
        $data['createdTime']=date('Y-m-d H:i:s',$list['creation_time']);
        $title = '';
            if ($list['standard'] == 2) {
                $title = '有影响-需要我自己处理';
            }
            if ($list['standard'] == 3) {
                $title = '有影响-今日无法施工';
            }
            
            $title=db('work_type', config('database.zong'))->where('id', $list['work_type'])->value('title');
            $work_process=db('work_process', config('database.zong'))->whereIn('id', $list['work_process_id'])->field('id,title')->select();
            foreach($work_process as  $k=>$item){
              $work_process[$k]['select']=1; 
            }
             $data['content']  = $title;
             $data['username']  = $list['username'];
             $data['fineUserId']  = $list['user_id'];
             $data['fineUserName']  = $list['fineUserName']??'';
             $data['orderId']  = $list['order_id'];
             $data['workList']  = [['title'=>$title,'select'=>1,'id'=>$list['work_type'],'date'=>$work_process]];
             $data['workTime']  = $list['work_time'];
             $data['auditRemarks']  = $list['audit_remarks'];
             $data['remarks']  = $list['remarks'];
             $data['imgs']  =empty($list['imgs']) ? null : unserialize($list['imgs']);
             $data['toPrice']  = $list['to_price'];
            if($list['to_price']==0){
              $data['toPrice']  = bcmul($list['price'],$list['work_time'],2);
            }
             

        r_date($data, 200);
    }
    
    /*
     * 材料外借
     */
    public function lend()
    {
        $data = Request::instance()->post();
        if ($this->us['Inventory'] == 1) {
            r_date(null, 300, '库存盘点中，无法领用，请盘点完成后操作');
        }
        $store_id=$this->us['store_id'];
        if(isset($data['orderId']) && $data['orderId'] !=0){
            $order=db('order')->where('order.order_id',$data['orderId'])->field('order.store_id,order.state')->find();
            if($order['state']<4 || $order['state']>7){
                r_date(null, 300, '请签约后在进行借调');
            }
            $store_id=$order['store_id'];
        }
        db()->startTrans();
        try {
            $time       = time();
            $company_id = db('company_config', config('database.zong'))->where('find_in_set(:id,store_list)', ['id' => $store_id])->where('status', 1)->value('company_id');
            $ids        = db('routine_usage')->insertGetId(['store_id' => $data['user_id'], 'stock_name' => $data['invname'], 'latest_cost' => $data['nabprice'], 'number' => '-' . $data['number'], 'code' => $data['id'], 'status' => 0, 'created_time' => $time, 'company' => $data['measname'], 'secondment' => 1, 'types' => 2]);
            
            $id = db('routine_usage')->insertGetId(['store_id' => $store_id, 'user_id' => $this->us['user_id'], 'stock_name' => $data['invname'], 'latest_cost' => $data['nabprice'], 'number' => $data['number'], 'code' => $data['id'], 'status' => 0, 'created_time' => $time, 'company' => $data['measname'], 'secondment' => 1, 'types' => 2, 'order_id' => $data['orderId']]);
            
            db('secondment')->insertGetId(['debi_store_id' => $store_id, 'stock_name' => $data['invname'], 'latest_cost' => $data['nabprice'], 'debi' =>$store_id, 'number' => $data['number'], 'code' => $data['id'], 'company' => $data['measname'], 'created_time' => $time, 'remake' => $data['etRemark'], 'lender' => 0, 'lender_store_id' => $data['user_id'], 'lender_id' => $ids, 'debi_id' => $id, 'types' => 2, 'companyId' => $company_id]);
            db()->commit();
            r_date(null, 200);
            
        } catch (Exception $e) {
            db()->rollback();
            r_date(null, 300, $e->getMessage());
        }
    }
    
     /*
     * 可用戒掉列表
     */
    public function ItemLending(Common $common)
    {
        $request = Authority::param(['invclasscode']);

        // 1. 调用接口并解析数据（保留原逻辑）
        $dataStr = u8queryForOther($request['invclasscode'], $this->us['store_id']);
        $data = json_decode($dataStr, true);

        if ($data['status'] !== 'success' || empty($data['data'])) {
            return r_date(null, 200); // 直接返回空结果
        }

        $list = $data['data'];

        // 2. 提取批量处理所需的参数，建立索引映射
        $pkCorps = [];
        $indexMap = []; // 记录原数组索引与关键参数的映射
        foreach ($list as $k => $value) {
            $pkCorp = $value['pk_corp'] ?? '';
            $invClasscode = $value['invcode'] ?? '';
            if (!empty($pkCorp) && !empty($invClasscode)) {
                $pkCorps[] = $pkCorp;
                $indexMap[$k] = [
                    'pk_corp' => $pkCorp,
                    'invclasscode' => $invClasscode,
                    'nonhandnum' => $value['nonhandnum'] ?? 0
                ];
            }
        }

        // 3. 批量查询 u8c_corp 的 store_id（1次查询替代 N 次）
        $pkCorpStoreMap = [];
        if (!empty($pkCorps)) {
            $pkCorpStoreMap = Db::connect(config('database.zong'))
                ->table('u8c_corp')
                ->whereIn('pk_corp', array_unique($pkCorps))
                ->column('store_id', 'pk_corp'); // 格式：[pk_corp => store_id, ...]

        }

        // 4. 批量查询 store_megre 合并信息（1次查询替代 N 次）
        $storeIds = array_filter(array_values($pkCorpStoreMap)); // 过滤空store_id
        $storeMergeMap = [];
        if (!empty($storeIds)) {
            $storeMergeMap = Db::connect(config('database.zong'))
                ->table('store_megre')
                ->where('state', 1)
                ->whereIn('store_id', array_unique($storeIds))
                ->order('id', 'desc')
                ->column('m_store_id', 'store_id'); // 格式：[原store_id => 合并后store_id, ...]

        }

        // 5. 按「实际store_id + invclasscode」分组，避免重复计算
        $calcGroups = [];
        foreach ($indexMap as $k => $item) {
            $originalStoreId = $pkCorpStoreMap[$item['pk_corp']] ?? '';
            if (empty($originalStoreId)) {
                continue;
            }
            // 处理店铺合并，获取实际用于查询的store_id
            $actualStoreId = $storeMergeMap[$originalStoreId] ?? $originalStoreId;
            $invClasscode = $item['invclasscode'];
            // 生成唯一分组键（确保相同条件只计算一次）
            $groupKey = $actualStoreId . '|' . $invClasscode;
            $calcGroups[$groupKey]['params'] = [
                'store_id' => $actualStoreId,
                'invclasscode' => $invClasscode
            ];
            $calcGroups[$groupKey]['indexes'][] = $k; // 记录该分组对应的原数组索引
        }

        // 6. 批量计算每个分组的 materialCount（核心优化）
        $materialCountMap = [];
        foreach ($calcGroups as $group) {
            $params = $group['params'];
            $storeId = 4;
            $invClasscode = $params['invclasscode'];

            // 6.1 批量查询 order_id（复用原逻辑）
            $orderIds = db('order')->where('store_id', $storeId)->whereIn("state", [4, 7])->where('order.cleared_time is  null or order.cleared_time =0')->column('order_id');

            // 6.2 批量计算 material_usage 总和（复用原逻辑）
            $materialUsage = 0;
            if (!empty($orderIds)) {
                $materialUsage = db('material_usage')
                    ->join('order', 'order.order_id = material_usage.order_id', 'left')
                    ->where('code', $invClasscode)
                    ->where('material_usage.status', 0)
                    ->whereIn('order.order_id', $orderIds)
                    ->group('code')
                    ->sum('square_quantity');
            }

            // 6.3 批量计算 secondment 总和（修复原逻辑的 whereIn 错误）
            $secondment = db('secondment')
                ->where('code', $invClasscode)
                ->whereIn('status', [0, 3])
                ->where('lender_store_id', $storeId) // 原代码误写为 whereIn（单个值用where）
                ->sum('number');

            // 6.4 合并结果并映射到所有相关索引
            $total = bcadd($materialUsage, $secondment, 2);
            foreach ($group['indexes'] as $k) {
                $materialCountMap[$k] = $total;
            }
        }

        // 7. 循环赋值（仅内存操作，无数据库查询）
        foreach ($list as $k => $value) {
            $materialCount = $materialCountMap[$k] ?? 0;
            $list[$k]['nonhandnum'] = bcsub(
                $value['nonhandnum'] ?? 0,
                $materialCount,
                2
            );
        }

        r_date($list, 200);
    }
    
    public function SecondmentDetails()
    {
        $data = Request::instance()->post();
        if ($data['type'] == 0) {
            $date   = db('custom_material')->where(['id' => $data['stock_id'], 'store_id' => $data['store_id'], 'status' => 0])->group('latest_cost')->field('id,sum(number) as number,stock_name,latest_cost')->select();
            $number = db('custom_material')->where(['id' => $data['stock_id'], 'store_id' => $data['store_id'], 'status' => 3])->sum('number');
        } elseif ($data['type'] == 99) {
            $date   = db('purchase_usage')->where(['id' => $data['stock_id'], 'store_id' => $data['store_id'], 'status' => 3])->group('latest_cost')->field('id,sum(number) as number,stock_name,latest_cost')->select();
            $number = db('purchase_usage')->where(['id' => $data['stock_id'], 'store_id' => $data['store_id'], 'status' => 3])->sum('number');
        } elseif ($data['type'] == 98) {
            $date = db('cooperation_usage')->where(['id' => $data['stock_id'], 'status' => 3])->group('latest_cost')->field('id,stock_name,latest_cost')->select();;
            $number = db('cooperation_usage')->where(['id' => $data['stock_id'], 'status' => 3])->sum('number');
        } else {
            $date   = db('routine_usage')->where(['stock_id' => $data['stock_id'], 'store_id' => $data['store_id'], 'status' => 3])->group('latest_cost')->field("id,stock_name,latest_cost")->select();
            $number = db('routine_usage')->where(['stock_id' => $data['stock_id'], 'store_id' => $data['store_id'], 'status' => 3])->sum('number');
        }
        if (count($date) > 1) {
            $id = implode(array_column($date, 'id'), ',');
        } else {
            $id = $date[0]['id'];
        }
        
        
        r_date(['num' => $number, 'stock_name' => $date[0]['stock_name'], 'latest_cost' => $date[0]['latest_cost'], 'id' => $id], 200);
        
    }
    
    /*
     * 借用记录
     */
    public function QuitTheList()
    {
        $date = Authority::param(['invclcode']);
        //Debit1借方2出借方
        $secondment = \db('secondment')->field('secondment.stock_name,secondment.id,secondment.latest_cost,FROM_UNIXTIME(secondment.created_time,"%Y-%m-%d %H:%i:%s") as created_time,sum(secondment.number) as number,user.username,secondment.status,secondment.company,secondment.content,secondment.debi_store_id,secondment.debi_id');
        if (isset($date['invclcode']) && $date['invclcode'] != '') {
            $secondment->where('secondment.code', $date['invclcode']);
        }
        $data = $secondment->join('user', 'user.user_id=secondment.debi', 'left')->where('secondment.category',1)->where('secondment.debi_store_id', $this->us['store_id'])->group('secondment.stock_id,secondment.created_time,secondment.debi')->select();
        foreach ($data as $k => $i) {
            $data[$k]['Debit'] = 1;
            $data[$k]['ids']   = $i['debi_id'];
        }
        $secondments = \db('secondment')->field('secondment.stock_name,secondment.debi_id,secondment.id,secondment.latest_cost,FROM_UNIXTIME(secondment.created_time,"%Y-%m-%d %H:%i:%s") as created_time,sum(secondment.number) as number,user.username,secondment.content,secondment.company,secondment.status,secondment.debi_store_id');
        if (isset($date['invclcode']) && $date['invclcode'] != '') {
            $secondments->where('secondment.code', $date['invclcode']);
        }
        $secondments = $secondments->join('user', 'user.user_id=secondment.debi', 'left')->where('secondment.category',1)->where('secondment.lender_store_id', $this->us['store_id'])->group('secondment.stock_id,secondment.created_time,secondment.debi')->select();
        
        foreach ($secondments as $k => $i) {
            $secondments[$k]['Debit'] = 2;
            $secondments[$k]['ids']   = $i['debi_id'];
        }
        $userArrayList = array_values(array_merge($data, $secondments));
        $arr_key       = array_column($userArrayList, 'created_time');
        array_multisort($arr_key, SORT_DESC, $userArrayList);
        r_date($userArrayList, 200);
    }
    
    /*
     * 戒掉审批列表
     */
    public function routineUusageApproval()
    {
         $date       = Request::instance()->post();
        $secondment = \db('secondment')->where('code', '<>', 0)->whereNotNull('code')->field('secondment.stock_name,secondment.id,secondment.latest_cost,FROM_UNIXTIME(secondment.created_time,"%Y-%m-%d %H:%i:%s") as created_time,sum(secondment.number) as number,`secondment`.`status`,secondment.category,secondment.debi');
        if (!empty($date['created_time']) && $date['created_time'] != '' && !empty($date['end_time']) && $date['end_time'] != '') {
            $start = strtotime($date['created_time'] . ' 00:00:00');
            $end   = strtotime($date['end_time'] . ' 23:59:59');
            $secondment->whereBetween('secondment.created_time', [$start, $end]);
        }
        $data = $secondment->where('secondment.lender_store_id', $this->us['store_id'])->whereIn('secondment.status',[0,1,2])->group('secondment.stock_id,secondment.created_time,secondment.debi')->order('secondment.id desc')->select();
        foreach($data as $k=>$item){
            if($item['category']==1){
                 $username="（店长）".\db('user')->where('user_id', $item['debi'])->value('username');
            }else{
                $username="（师傅）".\db('app_user')->where('id', $item['debi'])->value('username');
            }
            $data[$k]['username']=$username;
        }
        if($this->us['reserve']==2){
            $data=null;
        } 
        r_date($data, 200);
    }
    
    /*
     * 戒掉审批详情
     */
    public function routineUusageApprovalInfo()
    {
        $date       = Request::instance()->post();
        $secondment = \db('secondment')->field('secondment.stock_name,stock_id,lender_store_id,secondment.latest_cost,FROM_UNIXTIME(secondment.created_time,"%Y-%m-%d %H:%i:%s") as created_time,secondment.number,secondment.remake,user.username,if(secondment.category=1,user1.username, app_user.username)as username1,secondment.status,user2.username as username2')->join('user', 'user.user_id=secondment.lender', 'left')->join('user user1', 'user1.user_id=secondment.debi', 'left')->join('app_user', 'app_user.id=secondment.debi', 'left')->join('user user2', 'user2.user_id=secondment.reviewer', 'left')->where('secondment.id', $date['id'])->find();
        
        
        $secondment['number'] = \db('secondment')->where('created_time', strtotime($secondment['created_time']))->where('stock_id', $secondment['stock_id'])->where(['lender_store_id' => $secondment['lender_store_id']])->sum('number');
        r_date($secondment, 200);
    }
    
    /*
     * 戒掉审批审核
     */
    public function toExamine(Common $common,RedisPackage $redis)
    {
        $request = Authority::param(['id', 'status', 'content']);
        if ($this->us['Inventory'] == 1) {
            r_date(null, 300, '库存盘点中，无法领用，请盘点完成后操作');
        }
        $secondment = \db('secondment')->join('routine_usage', 'routine_usage.id=secondment.debi_id', 'left')->field('routine_usage.order_id,secondment.*')->where('secondment.id', $request['id'])->find();
        if(isset( $secondment['order_id']) &&  $secondment['order_id'] !=0){
            $order=db('order')->where('order.order_id',$secondment['order_id'])->field('order.store_id,order.state,order.assignor')->find();
            if($order['state']<4 || $order['state']>7){
                r_date(null, 300, '请签约后在进行借调');
            }
         
        }
        $store_id=$secondment['lender_store_id'];
        $antiDuplication='jie';
        $expire=10;
        // 设置缓存 设置缓存过期时间
        $tt=$redis->get(md5($request['id'].$antiDuplication));
        if ($tt) {
            r_date(null, 300, "请勿重复提交");
        }
        $redis->set(md5($request['id'].$antiDuplication), md5($request['id'].$antiDuplication),$expire);
        if ($request['status'] == 1 && !empty($secondment['order_id'])) {
            $invclcode=db('u8c_invbasdoc', config('database.zong'))->where('invname',$secondment['stock_name'])->value('invclcode');
            $material_usage = db('material_usage')->insertGetId(['order_id' => $secondment['order_id'], 'material_name' => $secondment['stock_name'], 'Material_id' => 0, 'square_quantity' => $secondment['number'],'unit_price' => 0,  'type' => 0, 'company' => $secondment['company'], 'lend'=>2,'total_price' =>0, 'user_id' => $secondment['debi'], 'created_time' => time(), 'shopowner_id' => isset($order)?$order['assignor']:0, 'adopt' => 0, 'status' =>0,  'types' => $secondment['category'], 'code' => $secondment['code'], 'invclasscode' => $invclcode]);
            db('usage_record')->insertGetId(['id' => $material_usage, 'type' => 0, 'user_id' => $secondment['debi'], 'number' => $secondment['number'], 'created_time' => time(), 'order_id' => $secondment['order_id'], 'original_number' => $secondment['number'], 'unified' => $invclcode]);
        }
        db()->startTrans();
        try {
            if ($request['status'] == 1) {
                $op  = u8queryForStoreId($secondment['code'], $store_id);
                $u8c = json_decode($op, true);
                
                if ($u8c['status'] == 'success') {
                    $number = $u8c['data'];
                    if (!is_array($number)) {
                        $number = json_decode($u8c['data'], true);
                    }
                    
                    $Leftover = $number['datas'][0]['nnum'] - $secondment['number'];
                    if ($Leftover >= 0) {
                        $inter    = u8outAndIn($secondment['debi_store_id'], $secondment['code'], $secondment['number'], $secondment['lender_store_id'], $secondment['companyId'], $request['id']);
                        $U8cinter = json_decode($inter, true);
                        if ($U8cinter['status'] != 'success') {
                            throw new Exception('审核失败');
                        }
                        if (!empty($secondment['order_id'])) {
                            $inter    = u8insertU8c($secondment['debi_store_id'], $secondment['order_id'], $secondment['number'], $secondment['code'], 0, $material_usage);
                            $U8cinter = json_decode($inter, true);
                            if ($U8cinter['status'] != 'success') {
                                throw new Exception($U8cinter['errormsg']);
                            }
                            $materialCostSellingPrice = $U8cinter['data']['materialCostSellingPrice'];//材料成本售价
                            $materialCostUnitPrice = $U8cinter['data']['materialCostUnitPrice'];// 材料成本单价
                            $total_price      =  round(($secondment['number'] * $materialCostSellingPrice),2);
                            $total_profit      =  round(($secondment['number'] * $materialCostUnitPrice),2);
                            db('material_usage')->where('id',$material_usage)->update(['total_price' =>$total_price,'total_profit' => $total_profit,'unit_price' => $materialCostSellingPrice,'status' => 1,'adopt' => time()]);
                            
                            
                        }
                        
                    } else {
                        throw new Exception('库存不足');
                    }
                    
                } else {
                    throw new Exception('请求异常，请稍后再试');
                }
            }
            $content = '';
            if ($request['status'] == 2) {
                $content = $request['content'];
            }
            $common->approvalReminder(['money' => round($secondment['latest_cost'] * $secondment['number'], 2), 'user_type' => 1, 'user_id' => $secondment['debi'], 'reject_user' => $this->us['username'], 'reject_desc' => $content, 'approval_status' => $request['status'], 'approval_time' => time(), 'type' => 10, 'title' => $secondment['stock_name'] . $secondment['number'] . $secondment['company'], 'city_id' => config('cityId'), 'relation_id' => $secondment['id']]);
            db('secondment')->where('id', $secondment['id'])->update(['status' => $request['status'], 'adopt' => time(), 'reviewer' => $this->us['user_id'], 'content' => $request['content']]);
            db('routine_usage')->where('id', $secondment['lender_id'])->update(['status' => $request['status'], 'adopt' => time(), 'content' => $request['content']]);
            db('routine_usage')->where('id', $secondment['debi_id'])->update(['status' => $request['status'], 'adopt' => time(), 'content' => $request['content']]);
            db()->commit();
            r_date(null, 200);
            
        } catch (Exception $e) {
            db()->rollback();
            if(isset($material_usage) && $material_usage !=0){
                db('material_usage')->where('id',$material_usage)->delete();
                db('usage_record')->where('id',$material_usage)->delete();
            }
            r_date(null, 300, $e->getMessage());
            
        }
    }
    /***********************************************返工后的材料已经报销***********************************************************************************/
    
    /*
     * 获取材料领用记录
     */
    public function CollectionRecord()
    {
        $date           = Request::instance()->post();
        $material_usage = db('material_usage')->field('app_user.username as sfusername,user.username as dzusername,material_usage.square_quantity,material_usage.code as Material_id,material_usage.types,material_usage.material_name,material_usage.unit_price')->join('usage_record', 'usage_record.id=material_usage.id', 'left')->join(config('database.db2')['database'] . '.app_user', 'app_user.id=material_usage.user_id and material_usage.types=2', 'left')->join('user', 'user.user_id = material_usage.user_id and material_usage.types=1', 'left')->where('material_usage.order_id', $date['order_id'])->where('usage_record.classification', 0)->where('material_usage.status', 1)->select();
        foreach ($material_usage as $k => $item) {
            if ($item['types'] == 2) {
                $material_usage[$k]['username'] = $item['sfusername'];
            } else {
                $material_usage[$k]['username'] = $item['dzusername'];
            }
            unset($material_usage[$k]['sfusername'], $material_usage[$k]['dzusername']);
        }
        
        r_date($material_usage, 200);
    }
    
    /*
     * 返工详情保存
     */
    public function constructionPlan()
    {
        $date = Request::instance()->post();
        
        db()->startTrans();
        try {
            $sql = 'select concat(unix_timestamp(now()), lpad(max(right(after_sales_no , 6)) + 1 , 6 , 0)) as sp from rework_end';
            //原生sql
            $reality_artificial = db('rework_end');
            $sum                = $reality_artificial->query($sql);
            if( (isset($date['id']) && $date['id']==0) || !isset($date['id'])){
                $end_id             = db('rework_end')->insertGetId(['img' => !empty(json_decode($date['img'], true)) ? serialize(json_decode($date['img'], true)) : '', 'order_id' => $date['order_id'],//材料id
                    'created_time' => time(), 'source' => 5, 'after_sales_no' => $sum[0]['sp'],'user_id'=>$this->us['user_id'],'description'=>'','attachment'=>'','completion_img'=>'','dispatch_time'=>time(),'initiation_time'=>time(),'update_time'=>0]);
            }else{
                $end_id=$date['id'];
            }
            
            db('order_rework')->insertGetId(['user_id' => $this->us['user_id'], 'order_id' => $date['order_id'],//材料id
                'customer' => 2, 'reason' => $date['remark'], 'rework_end' => $end_id]);
            $master    = isset($date['master']) ? json_decode($date['master'], true) : '';
            $material  = isset($date['material']) ? json_decode($date['material'], true) : '';
            $shopoWner = isset($date['shopoWner']) ? json_decode($date['shopoWner'], true) : '';
            $listArray['confirmed_time']=time();
            $listArray['construction']=1;
            $listArray['type']=$date['afterType'];
            $listArray['remark']=$date['remark'];
            if (empty($master) && empty($material) && empty($shopoWner)) {
                $listArray['update_time']=time();
                $listArray['construction']=2;
            }
            db('rework_end')->where('id', $end_id)->update($listArray);
            if (!empty($shopoWner)) {
                foreach ($shopoWner as $item) {
                    \db('rework_form')->insertGetId(['material_id' => '',//材料id
                        'capital_id' => $item['id'],//材料id
                        'user_id' => $this->us['user_id'],//店长id
                        'order_id' => $date['order_id'],//材料id
                        'created_time' => time(),
                        'type' => 1,//店长id  1方案原因2施工原因3材料原因
                        'end_id' => $end_id,//店长id  1方案原因2施工原因3材料原因
                    ]);
                    
                }
            }
            if (!empty($master)) {
                foreach ($master as $item) {
                    foreach ($item['arrayList'] as $key) {
                        \db('rework_form')->insertGetId(['material_id' => '',//材料id
                            'capital_id' => $key,//材料id
                            'order_id' => $date['order_id'],//材料id
                            'created_time' => time(),
                            'user_id' => $item['id'],//店长id
                            'type' => 2,//店长id  1方案原因2施工原因3材料原因
                            'end_id' => $end_id,//店长id  1方案原因2施工原因3材料原因
                        ]);
                        
                    }
                    $order = OrderModel::get(['order_id', $date['order_id']]);
                    if ($order->state > 5) {
                        $type = 1;
                    } else {
                        $type = 2;
                    }
                    $result  = send_post(UIP_SRC . "/support-v1/rework/add", ['order_id' => $date['order_id'], 'user_ids' => $item['id'], 'type' => $type, 'source' => 2, 'reason' => $date['remark'], 'city' => config('city')]);
                    $results = json_decode($result, true);
                    
                    if ($results['code'] != 200) {
                        throw  new  Exception($results['msg']);
                    }
                }
            }
            if (!empty($material)) {
                foreach ($material as $item) {
                    if (!empty($item['arrayList'])) {
                        foreach ($item['arrayList'] as $key) {
                            \db('rework_form')->insertGetId(['material_id' => $item['id'],//材料id
                                'capital_id' => $key,//材料id
                                'order_id' => $date['order_id'],//材料id
                                'user_id' => '',//店长id
                                'created_time' => time(), 'type' => 3,//店长id  1方案原因2施工原因3材料原因
                                'end_id' => $end_id,//店长id  1方案原因2施工原因3材料原因
                            ]);
                        }
                    } else {
                        \db('rework_form')->insertGetId(['material_id' => $item['id'],//材料id
                            'capital_id' => '',//材料id
                            'order_id' => $date['order_id'],//材料id
                            'user_id' => '',//店长id
                            'created_time' => time(), 'type' => 3,//店长id  1方案原因2施工原因3材料原因
                            'end_id' => $end_id,//店长id  1方案原因2施工原因3材料原因
                        ]);
                    }
                    
                }
            }
            db()->commit();
            r_date(null, 200);
        } catch (Exception $e) {
            db()->rollback();
            r_date(null, 300, $e->getMessage());
            
        }
        
        
    }
    
    /*
     * 返工详情回显
     */
    public function constructionPlanInfo()
    {
        $date          = Request::instance()->post();
        $afterType               = [['id'=>1,'title'=>'施工质保售后','selected'=>0],[ 'id'=>2,'title'=>'主材质保售后','selected'=>0],['id'=>3,'title'=>'超质保期施工售后','selected'=>0],['id'=>4,'title'=>'超质保期主材售后','selected'=>0]];
        $end_id        = db('rework_end')->where(['order_id' => $date['order_id'], 'id' => $date['id']])->find();
        foreach ($afterType  as $k=>$l){
            if($l['id']==$end_id['type']){
                $afterType[$k]['selected']=1;
            }
        }
        if($end_id['id']==0){
            r_date(['material' => empty($data) ? [] : $data, 'master' => empty($MasterData) ? [] : $MasterData, 'shopoWner' => empty($shopoWnerData) ? [] : $shopoWnerData, 'info' => $end_id,'afterType'=>$afterType], 200);
        }
        $end_id['img'] = empty($end_id['img']) ? [] : unserialize($end_id['img']);
        $rework_form   = db('rework_form')->where('rework_form.end_id', $end_id['id'])->select();
        foreach ($rework_form as $k => $item) {
            if ($item['type'] == 1) {
                $shopoWner[] = $item;
            }
            if ($item['type'] == 2) {
                $master[] = $item;
            }
            if ($item['type'] == 3) {
                $material[] = $item;
            }
        }
        
        if (!empty($shopoWner)) {
            $capital_id    = array_column($shopoWner, 'capital_id');
            $shopoWnerData = \db('capital')->whereIn('capital_id', $capital_id)->field('class_b,square,company')->select();
        }
        
        
        //施工原因
        $outMaster = [];
        $masters   = empty($master) ? [] : $master;
        if (!empty($masters)) {
            foreach ($masters as $key => $v) {
                if (isset($out[$v['user_id']])) {
                    unset($masters[$key]);
                } else {
                    $outMaster[$v['user_id']] = $v;
                }
            }
            $outMasterArray = array_merge($outMaster);
            foreach ($outMasterArray as $k => $item) {
                $capital_id = [];
                foreach ($master as $l) {
                    if ($item['user_id'] == $l['user_id']) {
                        $capital_id[] = $l['capital_id'];
                    }
                    $MasterData[$k]['arrayList'] = empty($capital_id) ? [] : $capital_id;
                    $MasterData[$k]['name']      = Db::connect(config('database.db2'))->table('app_user')->where('id', $item['user_id'])->value('username');;
                }
                
            }
        }
        
        //材料原因
        $out       = [];
        $materials = empty($material) ? [] : $material;
        
        foreach ($materials as $key => $v) {
            
            if (isset($out[$v['material_id']])) {
                unset($materials[$key]);
            } else {
                $out[$v['material_id']] = $v;
            }
        }
        $outArray = array_values(array_merge($out));
        
        foreach ($outArray as $k => $item) {
            $capital_id = [];
            foreach ($material as $l) {
                if ($item['material_id'] == $l['material_id']) {
                    $capital_id[] = $l['capital_id'];
                }
                
                $data[$k]['arrayList']   = empty($capital_id[0]) ? [] : $capital_id;
                $data[$k]['user_id']     = $item['user_id'];
                $data[$k]['material_id'] = $item['material_id'];
                $lists                   = U8cIncode($item['material_id'], $this->us['store_id']);
                $lists                   = json_decode($lists, true);
                
                if ($lists['status'] == 'success') {
                    
                    $data[$k]['name'] = $lists['data']['invname'];
                } else {
                    $data[$k]['name'] = '';
                }
                
                
            }
            
        }
        
        r_date(['material' => empty($data) ? [] : $data, 'master' => empty($MasterData) ? [] : $MasterData, 'shopoWner' => empty($shopoWnerData) ? [] : $shopoWnerData, 'info' => $end_id,'afterType'=>$afterType], 200);
        
    }
    public function constructionList()
    {
        
        $date       = Request::instance()->post();
        $rework_end = db('rework_end')->join('order', 'order.order_id=rework_end.order_id', 'left')->where(['rework_end.order_id' => $date['order_id']])->field('rework_end.update_time,rework_end.remark,rework_end.id,order.rework_cleared_time')->order('rework_end.id desc')->select();
        foreach ($rework_end as $k => $item) {
            $rework_end[$k]['moneyCost']       = \db('rework_reimbursement')->where(['end_id' => $item['id'], 'status' => 1])->sum('money');
            $rework_end[$k]['mast']            = empty(db('order_rework')->where(['rework_end' => $item['id']])->value('master_id')) ? 0 : 1;
            $rework_end[$k]['MaterialScience'] = \db('rework_material_usage')->where(['end_id' => $item['id'], 'status' => 1])->sum('total_price');
            $rework_end[$k]['CaseClosed']      = empty($item['update_time']) ? 0 : 1;
            if (empty($item['remark']) && empty($item['rework_cleared_time'])) {
                $rework_end[$k]['state'] = 0;
            } elseif (!empty($item['remark']) && empty($item['rework_cleared_time']) && empty($item['update_time'])) {
                $rework_end[$k]['state'] = 1;
            } elseif (!empty($item['update_time']) && empty($item['rework_cleared_time'])) {
                $rework_end[$k]['state'] = 2;
            } elseif (!empty($item['rework_cleared_time'])) {
                $rework_end[$k]['state'] = 3;
            }
        }
        r_date($rework_end, 200);
    }
    
    /*
      * 返工后的材料费用提交
      */
    public function ReworkMaterialUsage(Approval $approval)
    {
        
        $data            = Request::instance()->post();
        $data['storeId'] = $this->us['store_id'];
        $material_usage  = json_decode($data['materialJson'], true);
        
        db()->startTrans();
        try {
            $company_id = db('order')->where(['order_id' => $data['order_id']])->value('company_id');
            if ($data['costRoleType'] == 2) {
                $cost_user_id = $this->us['user_id'];
            } elseif ($data['costRoleType'] == 3) {
                $cost_user_id = $this->us['store_id'];
            } elseif ($data['costRoleType'] == 4) {
                $cost_user_id = $company_id;
            } elseif ($data['costRoleType'] == 1) {
                $cost_user_id = $data['costUserId'];
            } elseif ($data['costRoleType'] == 5) {
                $cost_user_id = '02019999';
            }
            $p                  = 0;
            $material_usageList = [];
            foreach ($material_usage as $datum) {
                $pp = ['order_id' => $data['order_id'], 'material_name' => $datum['material_name'], 'Material_id' => 0, 'square_quantity' => $datum['square_quantity'], 'unit_price' => $datum['unit_price'], 'type' => $datum['type'], 'company' => $datum['company'], 'total_price' => round($datum['unit_price'] * $datum['square_quantity'], 2), 'user_id' => $this->us['user_id'], 'created_time' => time(), 'shopowner_id' => $this->us['user_id'], 'status' => 0, 'total_profit' => $datum['unit_price'] * $datum['square_quantity'], 'types' => 1, 'end_id' => $data['id'], 'code' => $datum['Material_id'], 'cost_role_type' => $data['costRoleType'], 'cost_user_id' => $cost_user_id];
                
                $material_usage = db('rework_material_usage')->insertGetId($pp);
                db('usage_record')->insertGetId(['id' => $material_usage, 'type' => $datum['type'], 'user_id' => $this->us['user_id'], 'number' => $datum['square_quantity'], 'created_time' => time(), 'order_id' => $data['order_id'], 'original_number' => $datum['square_quantity'], 'unified' => $datum['Material_id'], 'classification' => 1]);
                
                
                $p                    += $pp['total_price'];
                $material_usageList[] = [
                    'Material_id' => $datum['Material_id'],
                    'square_quantity' => $datum['square_quantity'],
                    'unit_price' => $datum['unit_price'],
                    'id' => $material_usage
                ];
                
            }
            
            if ((string)$p != $data['allMoney']) {
                
                throw new Exception('金额错误');
            }
            if (empty($material_usageList)) {
                throw new Exception('没有新的材料领用');
                
            }
            
            db()->commit();
            // U8cForList($material_usageList, $data['order_id'], $this->us['store_id'], 2);
            $approval->Reimbursement(implode(',', array_column($material_usageList, 'id')), $this->us['username'] . '返工材料领用', $this->us['username'], 11);
            sendOrder($data['order_id']);
            
            
            r_date(null, 200);
        } catch (Exception $e) {
            db()->rollback();
            r_date(null, 300, $e->getMessage());
        }
    }
    
    /*
  * 返工后费用报销
  */
    public function reworkReimbursement(Approval $approval)
    {
        
        $data = Request::instance()->post();
        db()->startTrans();
        try {
            $reimbursementList = db('reimbursement')->where(['order_id' => $data['order_id'], 'reimbursement_name' => $data['name'], 'money' => $data['money']])->find();
            $company_id        = db('order')->where(['order_id' => $data['order_id']])->value('company_id');
            if ($data['type'] == 4) {
                if (empty($data['receiptNumber'])) {
                    throw new Exception('收据编号不能为空');
                }
                
            }
            if (!empty($reimbursementList)) {
                throw new Exception('名称和金额重复');
            }
            $my_string                   = explode(',', str_replace('"', '', trim($data['img'], '"[""]"')));
            $data['work_wechat_user_id'] = $this->us['work_wechat_user_id'];
            $data['reserve']             = $this->us['reserve'];
//            if (empty($data['work_wechat_user_id'])) {
//                throw new Exception('请联系公司');
//            }
            $data['content'] = $data['remarks'];
            $title           = $this->us['username'] . '返工费用报销';

//            if ($wechatObj_data['errcode'] != 0) {
//                cache::set($data['order_id'], $wechatObj_data);
//                throw new Exception('企业微信提交失败');
//            }
//            sendZONG($wechatObj_data['sp_no'], 'BsAYLMzwwWDR2LiDaPhDPYfev85Hbny9WuJCeQDx6');
            $t1             = microtime(true);
            $t2             = microtime(true);
            $l              = ($t2 - $t1) * 1000;
            $capital_id     = json_decode($data['mainMaterialIds'], true);
            $mainMaterialId = array_column($capital_id, 'mainMaterialId');
            $io             = implode(',', $mainMaterialId);
            $sp_no          = substr(date('YmdHis') . $l, 0, 14);
            $cost_user_id   = 0;
            if ($data['costRoleType'] == 2) {
                $cost_user_id = $this->us['user_id'];
            } elseif ($data['costRoleType'] == 3) {
                $cost_user_id = $this->us['store_id'];
            } elseif ($data['costRoleType'] == 4) {
                $cost_user_id = $company_id;
            } elseif ($data['costRoleType'] == 1) {
                $cost_user_id = $data['costUserId'];
            } elseif ($data['costRoleType'] == 5) {
                $cost_user_id = '02019999';
            }
            $op                   = ['order_id' => $data['order_id'], 'reimbursement_name' => $data['name'], 'money' => $data['money'], 'voucher' => !empty($data['img']) ? serialize($my_string) : '', 'created_time' => time(), 'user_id' => $this->us['user_id'], 'status' => 0, 'sp_no' => $sp_no, 'content' => $data['content'], 'classification' => $data['type'], 'submission_time' => time(), 'shopowner_id' => $this->us['user_id'], 'payment_notes' => $data['payment_notes'], 'end_id' => $data['id'], 'capital_id' => $io, 'cost_role_type' => $data['costRoleType'], 'cost_user_id' => $cost_user_id];
            $rework_reimbursement = db('rework_reimbursement')->insertGetId($op);
            if (!empty($capital_id)) {
                foreach ($capital_id as $value) {
                    db('rework_reimbursement_relation')->insertGetId(['reimbursement_id' => $rework_reimbursement, 'capital_id' => $value['mainMaterialId'], 'bank_id' => $data['bankCardId'], 'money' => $data['money'], 'receipt_number' => isset($data['receiptNumber']) ? $data['receiptNumber'] : '']);
                }
            }
            $orderSMS = json_decode(sendOrder($data['order_id']), true);
            if ($orderSMS['code'] != 200) {
                throw new Exception('编辑失败');
            }
            db()->commit();
            $approval->Reimbursement($rework_reimbursement, $title, $this->us['username'], 18);
            r_date(null, 200);
        } catch (Exception $e) {
            db()->rollback();
            r_date(null, 300, $e->getMessage());
            
        }
        
        
    }
    
    /*
     * 返工费用报销列表
     */
    
    public function getReworkReimbursementList(Capital $capital)
    {
        $data = Request::instance()->post();
        //费用报销
        $exp = new \think\db\Expression('field(rework_reimbursement.status,0,3,1,2)');
        
        $reimbursement = db('rework_reimbursement')->where(['rework_reimbursement.end_id' => $data['id']])
            ->join('user', 'user.user_id=rework_reimbursement.user_id', 'left')
            ->join('user user1', 'user1.user_id=rework_reimbursement.cost_user_id', 'left')
            ->join('store', 'store.store_id=rework_reimbursement.cost_user_id', 'left')
            ->join('app_user', 'app_user.id=rework_reimbursement.cost_user_id', 'left')
            ->field('rework_reimbursement.reimbursement_name,rework_reimbursement.id,rework_reimbursement.money,rework_reimbursement.voucher,rework_reimbursement.created_time,rework_reimbursement.status,rework_reimbursement.remake, rework_reimbursement.content as remarks,rework_reimbursement.classification,rework_reimbursement.payment_notes,rework_reimbursement.submission_time as submissionTime,user.username,rework_reimbursement.adopt,rework_reimbursement.type,
       CASE
            WHEN rework_reimbursement.cost_role_type=1 THEN concat("师傅承担(",app_user.username,")")
             WHEN rework_reimbursement.cost_role_type=2   THEN concat("店长承担(",user1.username,")")
             WHEN rework_reimbursement.cost_role_type=3  THEN concat("店铺承担(",store.store_name,")")
             WHEN rework_reimbursement.cost_role_type=4  THEN  "公司承担"
             WHEN rework_reimbursement.cost_role_type=5  THEN  "供应商承担"
             WHEN rework_reimbursement.cost_role_type=0  THEN  "未定义承担者"
             END as costTitle')->order($exp)->select();
        
        
        foreach ($reimbursement as $k => $item) {
            
            $reimbursement[$k]['voucher'] = empty(unserialize($item['voucher'])) ? [] : unserialize($item['voucher']);
            $reimbursement_relation       = db('rework_reimbursement_relation')
                ->Join('bank_card', 'bank_card.bank_id=rework_reimbursement_relation.bank_id', 'left')
                ->field('bank_card.*,rework_reimbursement_relation.receipt_number')
                ->where('reimbursement_id', $item['id'])
                ->find();
            $type                         = 3;
            $reimbur                      = db('approval', config('database.zong'))->join('bi_user', 'bi_user.user_id=approval.nxt_id', 'left')->where('relation_id', $item['id'])->where('type', $type)->where('approval.city_id', config('cityId'))->value('bi_user.username');
            if ($item['type'] == 2 && empty($reimbur)) {
                $reimbursement[$k]['reviewedBy'] = $this->us['username'];
            } else {
                $reimbursement[$k]['reviewedBy'] = !empty($reimbur) ? $reimbur : null;
            }
            
            $reimbursement[$k]['submissionTime'] = !empty($item['submissionTime']) ? date('Y-m-d H:i', $item['submissionTime']) : null;
            $reimbursement[$k]['createdTime']    = !empty($item['created_time']) ? date('Y-m-d H:i', $item['created_time']) : null;
            $reimbursement[$k]['adopt']          = !empty($item['adopt']) ? date('Y-m-d H:i', $item['adopt']) : null;
            
            $title                                = array_search($item['classification'], array_column($this->list_reimbursement_type(2), 'type'));
            $reimbursement[$k]['title_secondary'] = $this->list_reimbursement_type(2)[$title]['name'];
            if (!empty($item['secondary_classification'])) {
                $title_secondary                      = array_search($item['secondary_classification'], array_column($this->list_reimbursement_type(2), 'type'));
                $reimbursement[$k]['title_secondary'] = $reimbursement[$k]['title_secondary'] . '_' . $this->list_reimbursement_type(2)[$title_secondary]['name'];;
            }
            $reimbursement[$k]['receipt_number'] = isset($reimbursement_relation) ? $reimbursement_relation['receipt_number'] : '';
            if ($reimbursement_relation['category'] == 1 && $reimbursement_relation['binding_uid'] == $this->us['user_id']) {
                $reimbursement_relation['isMy'] = 1;
            } else {
                $reimbursement_relation['isMy'] = 0;
            }
            if ($item['classification'] != 4) {
                $reimbursement_relation = db('reimbursement_relation')
                    ->join('bank_card', 'bank_card.bank_id=reimbursement_relation.bank_id', 'left')
                    ->where('reimbursement_id', $item['id'])
                    ->field('bank_card.account_name as name,bank_card.bank_card_number as collection_number,capital_id ')
                    ->find();
                if (empty($reimbursement_relation)) {
                    $reimbursement_relation['name']              = '';
                    $reimbursement_relation['collection_number'] = '';
                }
                $reimbursement[$k]['reimbursementList'] = $reimbursement_relation;
                $array                                  = [];
                if (!empty($reimbursement_relation['capital_id'])) {
                    $capitalList = $capital
                        ->with('SpecsList')
                        ->where(['types' => 1, 'enable' => 1, 'agency' => 0])
                        ->whereIn('capital_id', $reimbursement_relation['capital_id'])
                        ->select();
                    
                    foreach ($capitalList as $k1 => $item1) {
                        $array[$k1]['capital_id'] = $item1['capital_id'];
                        $array[$k1]['class_b']    = $item1['class_b'];
                        $array[$k1]['company']    = $item1['company'];
                        $array[$k1]['square']     = $item1['square'];
                        $array[$k1]['un_Price']   = $item1['un_Price'];
                        $array[$k1]['to_price']   = $item1['to_price'];
                        $array[$k1]['specsList']  = implode('/', array_column($item1['specs_list'], 'option_value_title'));
                    }
                }
                
                $reimbursement[$k]['mainMaterialIds'] = $array;
            }
            
        }
        
        r_date($reimbursement, 200);
    }
    
    /*
    * 返工材料报销列表
    */
    
    public function getReworkMaterialUsageList()
    {
        $data = Request::instance()->post();
        //材料领用
        $material_usage = db('rework_material_usage')->where(['end_id' => $data['id']])
            ->join('user user1', 'user1.user_id=rework_material_usage.cost_user_id', 'left')
            ->join('store', 'store.store_id=rework_material_usage.cost_user_id', 'left')
            ->join('app_user', 'app_user.id=rework_material_usage.cost_user_id', 'left')
            ->field('code as Material_id,rework_material_usage.material_name,rework_material_usage.type,rework_material_usage.square_quantity,rework_material_usage.total_price,rework_material_usage.company,rework_material_usage.unit_price,rework_material_usage.created_time,rework_material_usage.id,rework_material_usage.status, CASE
            WHEN rework_material_usage.cost_role_type=1 THEN concat("师傅承担(",app_user.username,")")
             WHEN rework_material_usage.cost_role_type=2   THEN concat("店长承担(",user1.username,")")
             WHEN rework_material_usage.cost_role_type=3  THEN concat("店铺承担(",store.store_name,")")
             WHEN rework_material_usage.cost_role_type=4  THEN  "公司承担"
             WHEN rework_material_usage.cost_role_type=5  THEN  "供应商承担"
             WHEN rework_material_usage.cost_role_type=0  THEN  "未定义承担者"
             END as costTitle')->order('rework_material_usage.status asc')->select();
        r_date($material_usage, 200);
    }
    
    /*
     * 返工费用承担比例
     */
    
    public function getReworkProportion()
    {
        $data = Request::instance()->post();
        //材料领用
        $material_usage = db('rework_form')->join(config('database.db2')['database'] . '.app_user', 'app_user.id=rework_form.user_id and rework_form.type=2', 'left')->join('user', 'user.user_id=rework_form.user_id and rework_form.type=1', 'left')->where(['rework_form.end_id' => $data['id']])->where(['rework_form.type' => ['neq', 3]])->field('rework_form.id,IF(rework_form.type=1,user.username,app_user.username) as username,sum(rework_form.proportion) as proportion,sum(rework_form.money) as money,rework_form.type')->group('rework_form.user_id')->select();
        
        $moneyCost       = \db('rework_reimbursement')->where(['end_id' => $data['id'], 'status' => 1])->sum('money');
        $MaterialScience = \db('rework_material_usage')->where(['end_id' => $data['id'], 'status' => 1])->sum('total_price');
        $end_id          = db('rework_end')->where(['id' => $data['id']])->field('cause_analysis,summary,total,end_img,proportion,material_proportion')->find();
        foreach ($material_usage as $key => $item) {
            $material_usage[$key]['money'] = sprintf('%.2f', $moneyCost + $MaterialScience);
        }
        r_date(['data' => $material_usage, 'money' => sprintf('%.2f', $moneyCost + $MaterialScience), 'cause_analysis' => $end_id['cause_analysis'], 'summary' => $end_id['summary'], 'end_img' => empty($end_id['end_img']) ? null : unserialize($end_id['end_img']), 'proportion' => $end_id['proportion'], 'material_proportion' => empty($end_id['material_proportion'])?0:$end_id['material_proportion']], 200);
    }
    
    /*
     * 返工费用承担比例提交
     */
    public function SubmissionOfCommitmentRatio()
    {
        $data = Request::instance()->post();
        if (empty($data['id'])) {
            r_date([], 300, '参数不存在');
        }
        db()->startTrans();
        try {
            db('rework_end')->where(['id' => $data['id']])->update(['material_proportion' => $data['material_proportion'], 'proportion' => $data['proportion'],]);
            if (!empty($data['shopMasterPro'])) {
                $shopMasterPro = json_decode($data['shopMasterPro'], true);
                foreach ($shopMasterPro as $item) {
                    if ($item['id']) {
                        \db('rework_form')->where('id', $item['id'])->update(['money' => $item['money'], 'proportion' => $item['proportion']]);
                    }
                }
            }
            db()->commit();
            r_date(null, 200);
        } catch (Exception $e) {
            db()->rollback();
            r_date(null, 300, $e->getMessage());
            
        }
        
    }
    
    /*
     * 返工费用承担比例提交
     */
    public function ClosingReport()
    {
        $data = Request::instance()->post();
        if (empty($data['id'])) {
            r_date(null, 300, '参数不存在');
        }
        $ApprovalMaterialScience = db('rework_material_usage')->where(['end_id' => $data['id'], 'status' => 0])->count();
        $ApprovalReimbursement   = db('rework_reimbursement')->where(['end_id' => $data['id'], 'status' => 0])->count();
        if ($ApprovalMaterialScience != 0) {
            r_date(null, 300, '返工材料正在审核中');
        }
        if ($ApprovalReimbursement != 0) {
            r_date(null, 300, '返工费用报销正在审核中');
        }
        $moneyCost       = \db('rework_reimbursement')->where(['end_id' => $data['id'], 'status' => 1])->select();
        $moneyCostSum    = 0;
        $oldMoneyCostSum = 0;
        foreach ($moneyCost as $list) {
            if ($list['adopt'] < 1664553600) {
                $oldMoneyCostSum += $list['money'];
            }
            $moneyCostSum += $list['money'];
        }
        $sysConfig             = db('sys_config', config('database.zong'))->where('keyss', 'agent_material_code')->where('statusss', 1)->value('valuess');
        $MaterialScienceSum    = 0;
        $oldMaterialScienceSum = 0;
        $MaterialScience       = db('rework_material_usage')->where(['end_id' => $data['id'], 'status' => 1])->where('adopt', '>', 1648742400)->where('invclasscode', $sysConfig)->select();
        foreach ($MaterialScience as $item) {
            if ($list['adopt'] < 1664553600) {
                $oldMaterialScienceSum += $list['total_profit'];
            }
            $MaterialScienceSum += $list['total_profit'];
        }
        
        
        $total_price      = db('rework_material_usage')->where(['end_id' => $data['id'], 'status' => 1])->where('if(adopt>=1648742400,invclasscode Not IN (' . $sysConfig . ') and adopt>1625162399,adopt>1625162399 )')->select();
        $totalPriceSum    = 0;
        $oldTotalPriceSum = 0;
        foreach ($total_price as $list) {
            if ($list['adopt'] < 1664553600) {
                $oldTotalPriceSum += $list['total_profit'];
            }
            $totalPriceSum += $list['total_profit'];
        }
        db('rework_end')->where(['id' => $data['id']])->update(['cause_analysis' => $data['cause_analysis'], 'summary' => $data['summary'], 'end_img' => !empty($data['img']) ? serialize(json_decode($data['img'], true)) : '', 'update_time' => time(), 'total' => sprintf('%.2f', $moneyCostSum + $MaterialScienceSum + $totalPriceSum),]);
        
        $re = db('rework_end')
            ->field('concat(p.province,c.city,y.county,order.addres) as  addres,order.cleared_time,order.settlement_time,order.order_id')
            ->join('order', 'order.order_id=rework_end.order_id', 'left')
            ->join('province p', 'order.province_id=p.province_id', 'left')
            ->join('city c', 'order.city_id=c.city_id', 'left')
            ->join('county y', 'order.county_id=y.county_id', 'left')
            ->where('rework_end.id', $data['id'])
            ->find();
        if (!empty($oldMaterialScienceSum)) {
            U8cMasters('收到' . $re['addres'] . '返工代购材料结算成本', sprintf('%.2f', $oldMaterialScienceSum), $re['order_id'], 41);
        }
        if (!empty($oldTotalPriceSum)) {
            U8cMasters('收到' . $re['addres'] . '返工材料结算成本', sprintf('%.2f', $oldTotalPriceSum), $re['order_id'], 35);
        }
        if (!empty($oldMoneyCostSum)) {
            U8cMasters('收到' . $re['addres'] . '返工费用结算成本', sprintf('%.2f', $oldMoneyCostSum), $re['order_id'], 32);
        }
        
        
        r_date(null, 200);
        
        
    }
    
    public function reimbursement(Reimbursement $appReimbursement)
    {
        $params = Request::instance()->post();
        $list   = $appReimbursement->List($this->us['user_id'], strtotime($params['startTime']), $params['page'], $params['limit']);
        r_date($list, 200);
        
    }
    
    
    public function reimbInfo(Reimbursement $appReimbursement)
    {
        $params = Request::instance()->post();
        $list   = $appReimbursement->ListInfo($this->us['user_id'], $params['startTime']);
        
        foreach ($list as $k => $item) {
            $title = array_search($item->classification, array_column($this->list_reimbursement_type(2), 'type'));
            if (!empty($item['secondary_classification'])) {
                $title2                  = array_search($item['secondary_classification'], array_column($this->list_reimbursement_type(2), 'type'));
                $item['title_secondary'] = '_' . $this->list_reimbursement_type(2)[$title2]['name'];
            } else {
                $item['title_secondary'] = '';
            }
            $item['title']   = $this->list_reimbursement_type(2)[$title]['name'] . '_' . $item['title_secondary'];
            $item['voucher'] = empty($item->voucher) ? [] : unserialize($item->voucher);
        }
        
        r_date($list, 200);
        
        
    }
    
    /*
     * 订单退款
     */
    public function paymentRefund(Approval $approval,OrderDeliveryManagerModel $deliveryManagerModel)
    {
        $data = Authority::param(['orderId', 'material', 'agency_material', 'reason', 'remarks', 'bankName', 'bankOfDeposit', 'accountName', 'bankCardNumber']);
        $params = Request::instance()->get();
        $IsStartupDelivere = $deliveryManagerModel->IsStartupDeliverer($data['orderId'], $this->us['user_id'], '');
        if (!empty($IsStartupDelivere)) {
            r_date(null, 300, '请接单后再操作');
        }
        if (empty($data['bankName'])) {
            r_date(null, 300, '请填写退款银行');
        }
        if (empty($data['accountName'])) {
            r_date(null, 300, '请填写退款银行帐户名称');
        }
        if (empty($data['bankCardNumber'])) {
            r_date(null, 300, '请填写退款银行银行卡号');
        }
        $success = db('payment_refund', config('database.zong'))->where('order_id', $data['orderId'])->where('success', 2)->count();
        if ($success > 0) {
            r_date(null, 300, '已有退款正在审核,请稍后提交');
        }
        if ($data['material'] + $data['agency_material'] <= 0) {
            r_date(null, 300, '退款总金额不能为0');
        }
        $list = db('payment')
            ->whereNotNull('cleared_time')
            ->where('orders_id', $data['orderId'])
            ->field('ifnull(sum(material),0) as material, ifnull(sum(agency_material),0) as agency_material')
            ->select();
        $state                = Db::table('order')->where('order_id', $data['orderId'])->field('cleared_time,settlement_time')->find();
        if ($list[0]['material'] < $data['material']) {
            r_date(null, 300, '主合同退款金额不能超过主合同收款金额');
        }
        if($data['material']>0 && !empty($state['cleared_time'])){
            r_date(null, 300, '主合同已结算');
        }
        if($data['agency_material']>0 && !empty($state['settlement_time'])){
            r_date(null, 300, '代购合同已结算');
        }
        if ($list[0]['agency_material'] < $data['agency_material']) {
            r_date(null, 300, '代购合同退款金额不能超过代购合同收款');
        }
        $isChargeback=0;
        $shutdownReason='';
        if($data['reason']=='施工取消或终止' && (($list[0]['material']- $data['material'])==0 && ($list[0]['agency_material']- $data['agency_material'])==0)){
            if (!empty($IsStartupDelivere)) {
                r_date(null, 300, '请接单后再操作');
            }
            $total_price    = db('material_usage')->where(['status' => ['<>', 2], 'order_id' => $data['orderId']])->sum('total_price');
            $_reimbursement = db('reimbursement')->where(['order_id' => $data['orderId'], 'status' => ['<>', 2]])->count();
            if ($total_price != 0 || $_reimbursement != 0) {
                r_date(null, 300, '有材料领用，或报销不能退单请走结算');
            }
            $reason         = json_decode($params['shutdownReason'], true);
            $OriginalReason = '';
            foreach ($reason as $item) {
                if (isset($item['selected']) && $item['selected'] == true) {
                    $OriginalReason .= $item['title'] . '-';
                    foreach ($item['data'] as $list) {
                        if (isset($list['selected']) && $list['selected'] == true) {
                            $reasons=isset($list['data']['reason'])?$list['data']['reason']:'';
                            $OriginalReason .= $list['title'] . '-' .$reasons. ',';
                            
                        }
                    }
                    
                }
            }
            $shutdownReason=$OriginalReason ;
            $isChargeback=1;
        }
        $rework_reimbursement = db('payment_refund', config('database.zong'))->insertGetId([
            'order_id' => $data['orderId'],
            'success' => 2,
            'type' => 1,
            'material' => $data['material'],
            'agency_material' => $data['agency_material'],
            'remarks' => $data['reason'],
            'reason' => $data['remarks'],
            'is_chargeback' => $isChargeback,
            'chargeback_reason' => $shutdownReason,
            'created_time' => time(),
            'user_id' => $this->us['user_id'],
            'money' => $data['material'] + $data['agency_material'],
            'bank_name' => $data['bankName'],
            'bank_of_deposit' => $data['bankOfDeposit'],
            'account_name' => $data['accountName'],
            'bank_card_number' => $data['bankCardNumber'],
        ]);
        $title                = $this->us['username'] . '的退款审批';
        $approval->Reimbursement($rework_reimbursement, $title, $this->us['username'], 20);
        
        r_date(null, 200);
    }
    
  /*
     * 订单列表
     */
    public function paymentRefundList(OrderModel $orderModel)
    {
        $data      = Authority::param(['orderId']);
        $listArray = db('payment_refund', config('database.zong'))
            ->join('order_info', 'order_info.order_id=payment_refund.order_id', 'left')
            ->join('order', 'order.order_id=payment_refund.order_id', 'left')
            ->join('approval', 'approval.relation_id=payment_refund.refund_id  and  approval.type=9', 'left')
            ->join('bi_user', 'bi_user.user_id=approval.nxt_id', 'left')
            ->where('payment_refund.user_id', $this->us['user_id'])
            ->where('order.order_id', $data['orderId'])
            ->where('payment_refund.type', 1)
             ->group('payment_refund.refund_id')
            ->field('concat(order_info.province,order_info.city,order_info.county,order.addres) as addres,order.order_no,payment_refund.money,payment_refund.success,payment_refund.payment_time,FROM_UNIXTIME(payment_refund.created_time,"%Y-%m-%d ")as createdTime,if(ifnull(payment_refund.approved_time,0) !=0,FROM_UNIXTIME(payment_refund.approved_time,"%Y-%m-%d ")," ") as cleared_time,bi_user.username,order.order_id,payment_refund.payment_id,payment_refund.reject,payment_refund.bank_name as bankName,payment_refund.bank_of_deposit as bankOfDeposit,payment_refund.account_name as accountName,payment_refund.bank_card_number as  bankCardNumber')
            ->select();
        foreach ($listArray as $k => $item) {
            $city = substr($item['order_id'], 0, 3);
            if ($city == config('city')) {
                $listArray[$k]['entry'] = db('payment')->where('payment_id', $item['payment_id'])->value('cleared_time');
            } else {
                $content                = $orderModel->UrbanAccess($city);
                $listArray[$k]['entry'] = Db::connect($content)->table('payment')->where('payment_id', $item['payment_id'])->value('cleared_time');
            }
            $listArray[$k]['paymentState']="未打款"; 
            $listArray[$k]['paymentTime']=''; 
            if($item['success']==1 && ($item['payment_time'] >0 || (strtotime($item['cleared_time'])<1743647087 && $item['cleared_time'] >0))){
                $listArray[$k]['paymentState']="已完成打款"; 
                if(strtotime($item['cleared_time'])<1743647087){
                    $paymentTime=date('Y-m-d H:i:s', strtotime($item['cleared_time']));
                }else{
                    $paymentTime=date('Y-m-d H:i:s', $item['payment_time']);
                } 
               
                $listArray[$k]['paymentTime']=$paymentTime;
            }
            unset( $listArray[$k]['payment_time']);
            
        }
        r_date($listArray, 200);
        
    }
    
    public function paymentRefundInfo()
    {
        
        $data = Authority::param(['orderId']);
        $list = db('payment')
            ->whereNotNull('cleared_time')
            ->where('orders_id', $data['orderId'])
            ->field('ifnull(sum(material),0) as material, ifnull(sum(agency_material),0) as agency_material')
            ->select();
            $listArray = db('payment_refund', config('database.zong')) ->where('payment_refund.user_id', $this->us['user_id'])
            ->where('payment_refund.order_id', $data['orderId'])->order('refund_id desc')->find();
            $listData='暂无退款记录';
            if(!empty($listArray)){
                if($listArray['success']==0){
                    $listData="待审核"; 
                }elseif($listArray['success']==2){
                    $listData="审核中"; 
                }elseif($listArray['success']==3){
                    $listData="被驳回"; 
                }elseif($listArray['success']==1 && ($listArray['payment_time']==0 &&  $listArray['approved_time']==0)){
                    $listData="已通过待打款"; 
                }elseif($listArray['success']==1 && ($listArray['payment_time'] >0 || ($listArray['approved_time']<1743647087 && $listArray['approved_time'] >0))){
                    $listData="已通过已打款"; 
                }
               
            }
        r_date(['material' => $list[0]['material'], 'agency_material' => $list[0]['agency_material'], 'reason' => [
            '施工取消或终止',
            '客户纠纷拒付尾款',
            '施工问题扣款',
            '订单优惠',
            '减项退款',
        ],'paymentRefund'=>$listData], 200);
        
    }
    
}